java - 集合排序(空列表()): cannot infer type-variable

标签 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());使其编译。

最佳答案

一个有点老的问题,但仍然没有公认的答案。

假设对象是可比较的,例如 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/

相关文章:

java - 如何获取字段的泛型参数类

java - Android:NoSuchMethodError 接口(interface)中有静态方法(使用 Retrolambda)

java - Maven 中的 Gephi 依赖项缺失 Artifact 0.9-快照

Java方法泛型理解

java - 导入的 Eclipse 项目未编译

eclipse - Maven 依赖项仅在命令行下载,不在 Eclipse 中下载

ios - Swift 泛型 - 无法将值转换为类型

java - Linux 中的字体比 Windows 中的字体大

java - 对 Java 集合进行排序和重复数据删除

java - 如何在 Android 应用程序 (sdk 8) 中阻止 InterstitialAd (GMS)