具有可比性的Java排序 [英] Java Sort with Comparable
问题描述
我有一个 Person
对象的 ArrayList
. Person
(人员)具有 name
(名称), age
(年龄)和 height
(高度).我的目标是对该 ArrayList< Person>
进行排序.我已经实现了 Comparable< Person>
并定义了 compareTo()
,但是当我尝试对其进行排序时,它给了我这个错误:
I have an ArrayList
of Person
objects. A Person
has name
, age
and height
. My goal is to sort this ArrayList<Person>
. I have implemented Comparable<Person>
and have defined compareTo()
but when I try to sort it, it give me this error:
ArrayList类型的sort(Comparator)方法不适用于参数()"
The method sort(Comparator) in the type ArrayList is not applicable for the argument ()"
我的理解是,如果您实现Comparable,然后定义 compareTo
,其他所有事情都会为您神奇地完成.
The way I understand is that if you implement Comparable and then define compareTo
everything else is magically done for you.
有人可以解释一下它如何工作以及为什么我会收到此错误吗?
Can some one explain how to this works and why I am getting this error?
推荐答案
在其中添加新元素时,您都可以使用使用 Comparable
接口对元素进行排序的结构:
Either you use a structure which uses the Comparable
interface to order its elements when you add a new element inside it :
TreeSet<Person> persons = new TreeSet<>();
Person personOne = ...
Person personTwo = ...
persons.add(personOne);
persons.add(personTwo);
要么使用 List
和 Collections.sort(List< T> list)
方法,该方法都将要排序的列表作为参数(存在重载)这种方法,但与您的情况无关):
Either you use a List
and the Collections.sort(List<T> list)
method which takes as argument the list you want to sort (there is an overload of this method but it is not relevant in your case):
List<Person> persons = new ArrayList<>();
Person personOne = ...
Person personTwo = ...
persons.add(personOne);
persons.add(personTwo);
Collections.sort(persons);
使用 TreeSet
,元素将在添加后立即排序,而使用 List
,则在添加元素时不对元素进行排序.调用 Collections.sort()
方法对列表进行排序.
With the TreeSet
, the elements are sorted as soon as added and with the List
, the elements are not sorted when you add them.
Only, the call to the Collections.sort()
method sorts the list.
这篇关于具有可比性的Java排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!