public void sortByLastName(){
Collections.sort(list, new Comparator<Person>() {
public int compare(Person p1, Person p2){
return p1.getLastName().compareTo(p2.getLastName());
}
} );
}
此处显示的代码是 contactList 数组的一部分,我按姓氏对列表进行排序,我似乎无法编译它,而且我看不出有什么问题。
编辑:编译器上的错误是
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method sort(List<T>, Comparator<? super T>) in the type Collections is not applicable for the arguments (Person[], new Comparator<Person>(){})
at ContactList.sortByLastName(ContactList.java:34)
at Main.main(Main.java:18)
最佳答案
sort(List, Comparator) in the type Collections is not applicable for the arguments (Person[], new Comparator(){})
这告诉您,采用 List
和 Comparator
的方法 Collections.sort()
与您提交的内容不匹配,您提交的内容似乎是 Person
对象 (Person[]
) 和 Comparator
的数组。 Java 中的数组和列表乍一看似乎很相似,但实际上它们是不同的。为了对对象数组进行排序,请使用 Arrays.sort()相反。
关于java - Collections.sort 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15628260/