Pet*_*xwl 2 java generics comparable
我是泛型和铸造问题的新手。我尝试对任何可比较的类型数组进行排序。错误如标题;代码如下:整数错误相同。有什么问题,为什么?
class Sort{
public static void selectionSort(Comparable<Object>[] input)
{/* selection Sort Alg*/}
public static void main((String[] args){
int[] intArray = {2,3,5,1};
Sort.selectionSort(intArray);
}
}
Run Code Online (Sandbox Code Playgroud)
你在这里有两个问题:
int
是一个 POD,而不是一个对象。不会自动执行从int[]
到对应的装箱和拆箱Integer[]
。您需要声明intArray
为:
Integer[] intArray = {2,3,5,1};
Run Code Online (Sandbox Code Playgroud)Integer
实现Comparable<Integer>
,不是Comparable<Object>
。这两种专业化是不同且不兼容的类型。正确的声明方法selectionSort
是使用泛型,正如您在标题中所建议的:
public static <T extends Comparable<T>> void selectionSort(T[] input)
Run Code Online (Sandbox Code Playgroud)