2012-04-19 3 views
0

タイプパラメータを含む汎用メソッドを含むプログラムを作成しようとしています。クラスPairのインスタンスを返すはずです。どのように私はペアを返すことができるか分からない。私が持っているコードは以下の通りです:汎用ペアを返します

public class MinMaxArray 
{ 
    public static <ArrayType extends Comparable<ArrayType>> 
       ArrayType getMinMax(ArrayType[] anArray) 
      throws IllegalArgumentException 
    { 
    try 
    { 


    ArrayType resultMin = anArray[0]; 
     ArrayType resultMax = anArray[0]; 
     for (int index = 1; index < anArray.length; index++) 
     if (result.compareTo(anArray[index]) < 0) 
      result = anArray[index]; 
     if (result.compareTo(anArray[index]) > 0) 
      result = anArray[index]; 


    return resultMin; 
    return resultMax; 
}//try 

    catch (ArrayIndexOutOfBoundsException e) 
    { throw new IllegalArgumentException("Array must be non-empty", e); } 
    catch (NullPointerException e) 
    { throw new IllegalArgumentException("Array must exist", e); } 
    }//getMinMax 
}//class MinMaxArray 

ペアクラスコード:

//Two onjects grouped into a pair. 
public class Pair<FirstType, SecondType> 
{ 
    //The first object. 
    private final FirstType first; 

    //The second object. 
    private final SecondType second; 

    //Constructor is given the two objects. 
    public Pair(FirstType requiredFirst, SecondType requiredSecond) 
    { 
    first = requiredFirst; 
    second = requiredSecond; 
    }//Pair 



    //Return the first object. 
    public FirstType getFirst() 
    { 
    return first; 
    }//GetFirst 


    //Return the second object. 
    public SecondType getSecond() 
    { 
    return second; 
    }//GetSecond 

}//class Pair 

私はresultMaxとresultMinがペアとして返すために得ることができるかどうかはわかりません。助けてくれてありがとう。おそらく、

答えて

2

public static <ArrayType extends Comparable<ArrayType>> 
      Pair<ArrayType, ArrayType> getMinMax(ArrayType[] anArray) { 
    ... 
    return new Pair<ArrayType, ArrayType>(resultMin, resultMax); 
} 
+0

Pavlol、テストプログラムの主な方法で、それをテストするためには、私のようなものを持つことができます: 'String []型aStringArray = { "こんにちは"、" 「何か」、「あなたの」、「名前」} ' – AkshaiShah

+0

確かに、進んでみてはどうですか? –

+0

@Pavlov最小値と最大値を返そうとしていますが、これを出力として取得しています。テスト用のメインメソッドにある 'Pair @ 10385c1'コードは次のとおりです。' String [] aStringArray = {" "、" cat "、" vaporised "、" on "、" the "、" mat "}; ペアminMaxInAStringArray = MinMaxArray.getMinMax(aStringArray); System.out.println(minMaxInAStringArray); '問題が何であるか不明?? – AkshaiShah

2

は私見私は

return new ArrayType[] { resultMin, resultMax }; 

か、ペアのクラスに

をファクトリメソッドを追加することができますを使用することになり

return new Pair<ArrayType, ArrayType>(resultMin, resultMax); 

を試してみてくださいあなたが書くことができ、その後

public static <FirstType, SecondType> Pair<FirstType, SecondType> of(FirstType first, SecondType second) { 
     return new Pair<FirstType, SecondType>(first, second); 
} 

return Pair.of(resultMin, resultMax); 
+0

私はペアのインスタンスを使用する必要があります。選択肢がありませんので、最初に試してみましょう。 1。ありがとう – AkshaiShah

+0

ファクトリメソッドを追加すると、より良いものにすることができます。 ;) –

+0

ファクトリメソッドについて聞いたことがない、面白いと思う、私はそれを見てみましょう:) – AkshaiShah

関連する問題