2014-01-15 30 views
0

我有一個通用的方法,檢查數組是否排序。但是,當我在我的主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[]) 
+1

在Java 7上編譯。 –

+0

您正在使用哪個版本的Java? –

+1

編譯並運行在Java 5-7上。 – rgettman

回答

0

你試過

public static <T extends Comparable<? extends T>> boolean isSorted(T[] arr) 

或簡單地

public static <T extends Comparable> boolean isSorted(T[] arr) 

+0

您已更改類型變量的範圍。 –

+0

@SotiriosDelimanolis對我來說,它似乎更有意義。 –

+0

編輯你的答案並解釋。 –

相關問題