【发布时间】: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