我有一個通用的方法,檢查數組是否排序。但是,當我在我的主Generic.isSorted(arr)
中寫入時,我立即出現錯誤。推斷的類型不符合上限(s)?
主:
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 7上編譯。 –
您正在使用哪個版本的Java? –
編譯並運行在Java 5-7上。 – rgettman