我正在尝试创建一个包含泛型方法的程序,该方法包含一个类型参数。它应该返回类 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 作为 Pair 返回。谢谢您的帮助。