这件事只是没有编译。我不知道自己做错了什么。编译器在 Collections.sort(用户); 咆哮。在程序列表后看到下面的错误消息。如果你能提供任何有关这段代码真正错误的见解,将不胜感激。
这里是 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
答案 0 :(得分:0)
您的代码可以使用JDK 1.7.0.60,1.7.0.80,1.8.0.25和1.8.0.40进行编译。可能你有一些早期的1.8.0.x javac,它在泛型方面存在很多问题。尝试将其更新到最新版本。
答案 1 :(得分:0)
如果您的编译器抱怨此问题,请尝试提供有关类型的提示:
Collections.<User>sort(users);