排序集的最佳方法是什么?

我有一个代表汽车的class级:

public class Car implements Comparable { String name; int value; ... @Override public int compareTo(Car o) { return name.compareTo(o.name); } } 

和另一个代表种族的类:

 public class Race { cars = new HashSet(); ... public Collection sortByName() { List carList = new ArrayList(cars); Collections.sort(carList); return carList; } } 

它是我对排序Set的实现,我知道有一个TreeSet但我不知道如何通过TreeSet而不是HashSet来比较它,因为如果我使用TreeSet我找不到方法comprator(),任何人都可以帮助我,如果我正在做好吧,如果不是如何使用TreeSet?

这是TreeSet javadoc的一个片段:

A NavigableSet implementation based on a TreeMap. The elements are ordered using their natural ordering, or by a Comparator provided at set creation time, depending on which constructor is used.

自然排序是指通过使Car类实现Comparable接口而强制执行的顺序。 只需将您的汽车添加到TreeSet实例中,它们就会为您排序。

使用Comparator而不是CarComparableComparator是它所比较的​​类的外部,而Comparable是该类的内部。 更详细的解释如下: https : //stackoverflow.com/a/4108764/1838970

现在,问你的问题。 实现此比较器:

 public class CarComparatorByName implements Comparator { public int compare(Car o1, Car o2) { return o1.getName().compareTo(o2.getName()); } } 

现在使用该Comparator创建一个TreeSet:

 Set cars = new TreeSet(new CarComparatorByName()); 

TreeSet现在将使用您创建的比较器。

或者,如下面的评论中所述,您可以将Car保留为Comparable并在创建时将它们简单地抛出到TreeSetTreeSet将使用Car implements Comparable定义的自然排序顺序。