返回通用对

时间:2012-04-19 13:35:53

标签: java generics instance

我正在尝试创建一个包含泛型方法的程序,该方法包含一个类型参数。它应该返回类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 个答案:

答案 0 :(得分:2)

也许,

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

答案 1 :(得分:2)

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

恕我直言,我会用

return new ArrayType[] { resultMin, resultMax };

或者您可以将工厂方法添加到Pair类

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

然后你可以写

return Pair.of(resultMin, resultMax);