什么? 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());
使其编译。
最佳答案
一个有点老的问题,但仍然没有公认的答案。
假设对象是可比较的,例如 String 类,我将简单地更改如下:
Collections.sort(Collections.<String>emptyList());
或者将其分为两步:
List<String> s = Collections.emptyList();
Collections.sort(s);
正如在原始问题中更新的那样,如果您不想对 Collections.emptyList()
进行任何更改,则以下内容也有效:
Collections.<Comparable<Object>>sort(Collections.emptyList());
关于java - 集合排序(空列表()): cannot infer type-variable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42800045/