Collections.sort(emptyList()):无法推断类型变量

时间:2017-03-15 02:26:17

标签: java eclipse generics java-8

什么? javac(1.8.0_121)发生此编译错误,但在Eclipse(4.6.2)中构建并运行良好。

以下是极其简化的代码:

import java.util.Collections;

public static void main(String[] args) {
    Collections.sort(Collections.emptyList());
}

(我不关心语义。原始代码不是Collections.sort(),而是具有类似签名的东西。)

为此,javac打印:

error: no suitable method found for sort(List<Object>)
                Collections.sort(Collections.emptyList());
                           ^
    method Collections.<T#1>sort(List<T#1>) is not applicable
      (inferred type does not conform to upper bound(s)
        inferred: Object
        upper bound(s): Comparable<? super Object>,Object)
    method Collections.<T#2>sort(List<T#2>,Comparator<? super T#2>) is not applicable
      (cannot infer type-variable(s) T#2
        (actual and formal argument lists differ in length))
  where T#1,T#2 are type-variables:
    T#1 extends Comparable<? super T#1> declared in method <T#1>sort(List<T#1>)
    T#2 extends Object declared in method <T#2>sort(List<T#2>,Comparator<? super T#2>)
1 error

我可以对javac进行编译吗?我应该只考虑Java 8中的限制并编写解决方法吗?

更改为Collections.<Comparable<Object>>sort(Collections.emptyList());会使其编译。

1 个答案:

答案 0 :(得分:0)

一个古老的问题,但仍然没有一个可以接受的答案。

假设对象是可比较的,例如String类,我将对此进行如下更改:

Collections.sort(Collections.<String>emptyList());

或将其分为两个步骤:

List<String> s = Collections.emptyList();
Collections.sort(s);

如果您不想对Collections.emptyList()进行任何更改,那么以下问题也可以在原始问题中进行更新:

Collections.<Comparable<Object>>sort(Collections.emptyList());