第一次来,这里的 Java 代码有问题: 导入java.util.*;
public class Pootis
{
public static void main(String[] args)
{
Superhero batman = new Superhero("Bruce", 26, "Batman");
Human rachel = new Human("Rachel", 24);
Superhero ironman = new Superhero("Tony", 35, "Ironman");
Human pepper = new Human("Pepper", 22);
List<Human> people = new ArrayList<>();
people.add(batman);
people.add(rachel);
people.add(ironman);
people.add(pepper);
Collections.sort(people);//<-----
}
}
这个程序的目的是对people ArrayList中的人按照年龄进行排序。我正在使用与此类似的界面。问题似乎出在调用 Collections.sort(people) 时。我做错了什么?? 这是第二堂课:
public class Human implements Comparable<Human> {
private int age;
private String name;
public Human(String givenName, int age) {
this.name = givenName;
this.age = age;
}
@Override
public int compareTo(Human other){
if(getAge() > other.getAge()){
return 1;
}
else if(getAge() < other.getAge()){
return -1;
}
return 0;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
这是错误:
Pootis.java:65: 错误: 没有找到适合排序(List) 的方法 Collections.sort(人); ^ 方法 Collections.sort(List,Comparator) 不适用 (无法从参数实例化,因为实际参数列表和形式参数列表的长度不同) 方法 Collections.sort(List) 不适用 (推断类型不符合声明的边界 推断:对象 界限:可比较) 其中 T#1,T#2 是类型变量: T#1 扩展了方法 sort(List,Comparator) 中声明的对象 T#2 扩展了方法 sort(List) 中声明的 Comparable 1 个错误
这是 super 英雄类:
public class Superhero {
String alterEgo, name;
int age;
public Superhero(String givenName, int age, String alterEgo) {
super();
this.alterEgo = alterEgo;
this.name = givenName;
this.age = age;
}
public String getAlterEgo() {
return alterEgo;
}
public String introduce() {
return "Hey! I'm " + name + " and I'm " + age + " years old. I'm also known as" + alterEgo + "!";
}
}
最佳答案
Collections.sort()
的签名是:
public static <T extends Comparable<? super T>> void sort(List<T> list)
这意味着您只能调用 sort
在 Comparable
的列表中对象。使用List<Object>
无效为 Object
不是Comparable
。 sort()
已重载
public static <T> void sort(List<T> list,
Comparator<? super T> c)
但这不适用于您的方法调用,因为您只提供了一个参数。
请记住,根据 javadoc,为了使用 Collections.sort()
对列表进行排序所有要素必须具有相互可比性。在你的情况下,这意味着你应该有一种方法来比较 Human
到 Superhero
。另外,如果Superhero extends Human
,您的列表应声明为 List<Human>
(或反之亦然)。
关于java - 使用 Comparable、Java 进行 Collections.sort 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34833538/