推断类型不符合上限?

时间:2014-01-15 16:42:28

标签: java generics java-8

我有一个通用方法来检查数组是否已排序。但是,当我在主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[])

1 个答案:

答案 0 :(得分:0)

你试过吗

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

或只是

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