我想在类中创建一个泛型方法,该方法接受给定类型对象的数组并对它们进行排序,以返回包含最小数组项和最大数组项的对象。
目前我遇到3个编译器错误:
public <FirstType> Pair sortMinMax(Object<FirstType>[] array)
Object<FirstType> minimum = array[0]
Object<FirstType> maximum = array[0]
这是我的班级:
public class MinMaxArray {
// takes an array of a given object and returns a pair
// of the min and max array elements
public <FirstType> Pair sortMinMax(Object<FirstType>[] array) {
Object<FirstType> minimum = array[0];
Object<FirstType> maximum = array[0];
// loop through all array items and perform sort
for (int counter = 1; counter < array.length; counter++) {
// if this element is less than current min, set as min
// else if this element is greater than current max, set as max
if (array[counter].compareTo(minimum) < 0) {
minimum = array[counter];
} else if (array[counter].comparTo(maximum) > 0) {
maximum = array[counter];
} // end if else new min, max
} // end for (all array items)
return new Pair<FirstType, FirstType>(minimum, maximum);
} // end compare()
} // end MinMaxArray
答案 0 :(得分:3)
首先,避免引用数组。他们在仿制药方面表现不佳。请改用List
。
如果您打算将FirstType
作为类型或通用参数(通常会给出单个字母名称),我不清楚。
如果FirstType
是类型
public static Pair<FirstType,FirstType> sortMinMax(List<FirstType> things) {
如果您指的是通用参数,请查看java.util.Collections.sort
。
public static <T extends Comparable<? super T>> void sort(List<T> list) {
所以
public static <T extends Comparable<? super T>> Pair<T,T> sortMinMax(List<T> list) {
答案 1 :(得分:1)
type Object does not take parameters
这是最能说明你的。简单地说,您可以编写Object<T>
之类的内容。类Object
未参数化。例如,List
是。
此外,为了使用compareTo()
方法,您需要具有以下内容:
public <FirstType extends Comparable> Pair sortMinMax(FirstType[] array)