【发布时间】:2014-01-15 16:42:27
【问题描述】:
我有一个通用方法来检查数组是否已排序。但是,当我写在我的主要Generic.isSorted(arr) 中时,我立即收到错误消息。
主要:
public static void main(String[] args) {
Integer [] arr = {1,3,8,4,2};
Generics.isSorted(arr); //error
}
通用方法:
public class Generics()
{
public static <T extends Comparable<? super T>> boolean isSorted(T[] arr)
{
if (arr == null || arr.length <= 1)
return true;
for (int i = 0; i < arr.length - 1; i++)
{ if (arr[i].compareTo(arr[i+1]) > 0)
{ return false;}
}
return true;
}
}
错误:
method isSorted in class Generics cannot be applied to given types;
required: T[]
found: Integer[]
reason: inferred type does not conform to upper bound(s)
inferred: Integer
upper bound(s): Comparable<? super Integer>
where T is a type-variable:
T extends Comparable<? super T> declared in method <T>isSorted(T[])
【问题讨论】:
-
您使用的是哪个版本的 Java?
-
在 Java 5-7 上编译和运行。
-
你有自己的
Integer类吗? -
我不知道这些能不能解决你的问题,但是1)你有语法问题(例如
public class Generics()),2)<T extends Comparable<T>>可能就足够了,3) 你必须循环直到arr.length - 2,并且 4) 一个数组可以包含nulls,所以要注意 NPE;) -
@sp00m 不是语法问题。
<T extends Comparable<? super T>>是正确的做法。