ant*_*tak 6 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());
}
Run Code Online (Sandbox Code Playgroud)
(我不关心语义.原始代码不是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
Run Code Online (Sandbox Code Playgroud)
有什么我可以做的javac编译吗?我是否应该将此视为Java 8中的限制并编写解决方法?
更改为Collections.<Comparable<Object>>sort(Collections.emptyList());使其编译.
有点老的问题,但仍然没有公认的答案。
假设对象是可比较的,例如 String 类,我只需将其更改如下:
Collections.sort(Collections.<String>emptyList());
Run Code Online (Sandbox Code Playgroud)
或将其分为两个步骤:
List<String> s = Collections.emptyList();
Collections.sort(s);
Run Code Online (Sandbox Code Playgroud)
正如原始问题中更新的那样,如果您不想进行任何更改,则以下内容也适用Collections.emptyList():
Collections.<Comparable<Object>>sort(Collections.emptyList());
Run Code Online (Sandbox Code Playgroud)