【问题标题】:no suitable method found for sort(List<User>)没有找到适合 sort(List<User>) 的方法
【发布时间】:2017-06-04 12:25:58
【问题描述】:

这个东西不会编译。我不知道我在做什么错。编译器在 Collections.sort(users); 咆哮。请参阅程序列表后下方的错误消息。如果您能提供任何关于那段代码真正错误的见解,我们将不胜感激。

这是命令java -version的输出:

java version "1.8.0_25"
Java(TM) SE Runtime Environment (build 1.8.0_25-b18)
Java HotSpot(TM) 64-Bit Server VM (build 25.25-b02, mixed mode)

.

import java.util.ArrayList;
import java.util.List;
import java.util.Collections;

class MyApp {
    public static void main(String[] args) {

        List<User> users = new ArrayList<>();

        users.add(new User("John Doe"));
        users.add(new User("Bob Smith"));
        users.add(new User("Jane Doe"));
        users.add(new User("Bill Gates"));

        Collections.sort(users);

        for (User user : users)
            System.out.println(user.name);
   }
}

class User implements Comparable<User> {
    public String name;
    User(String name) { this.name = name; }
    @Override public int compareTo(User user) {
        return this.name.compareTo(user.name);
    }
}

这是我收到的丑陋错误消息:

MyApp.java:15: error: no suitable method found for sort(List<User>)
            Collections.sort(users);
                   ^
    method Collections.<T#1>sort(List<T#1>) is not applicable
      (inference variable T#1 has incompatible bounds
        equality constraints: User
        upper bounds: Comparable<? super T#1>)
    method Collections.<T#2>sort(List<T#2>,Comparator<? super T#2>) is     not appli
cable
      (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

【问题讨论】:

  • 你用的是哪个java版本?
  • java 版本 "1.8.0_25" Java(TM) SE Runtime Environment (build 1.8.0_25-b18) Java HotSpot(TM) 64-Bit Server VM (build 25.25-b02, 混合模式)
  • 因为您要导入 ArrayList、List 和 Collections 但不是 Comparable,并且因为我以前见过这个:您是否定义了自己的名为 Comparable 的接口?
  • 不,我没有定义任何东西。清单中的代码就是全部。
  • 检查异常用法:同一个包中有MyApp.java和User.java?

标签: java


【解决方案1】:

您的代码可以在 JDK 1.7.0.60、1.7.0.80、1.8.0.25 和 1.8.0.40 上正常编译。可能你有一些早期的 1.8.0.x javac 有很多泛型问题。尝试将其更新到最新版本。

【讨论】:

  • java 版本 "1.8.0_25" Java(TM) SE Runtime Environment (build 1.8.0_25-b18) Java HotSpot(TM) 64-Bit Server VM (build 25.25-b02, 混合模式)
  • 嗯,当我下载并安装我的 Java 编译器时,大约是 5 或 6 个月前,它是当时的最新版本。所以,我不认为我的编译器那么旧。据我所知,泛型功能已经存在了很长时间。
【解决方案2】:

如果您的编译器对此有抱怨,请尝试给出有关类型的提示:

 Collections.<User>sort(users);

【讨论】:

  • 错误:类Collections中的方法排序不能用于给出n个类型;集合。排序(用户); ^ 必需:List 找到:List 原因:显式类型参数用户不符合声明的界限 Comparable super User> 其中 T 是一个类型变量: T extends Comparablesort(List) 中声明的 super T> 注意:一些消息已被简化;使用 -Xdiags:verbose 重新编译以获得完整的输出 1 错误
猜你喜欢
  • 1970-01-01
  • 2015-06-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-30
  • 2014-08-27
  • 2021-06-19
相关资源
最近更新 更多