Best way to sort a Set?

跟風遠走 提交于 2019-12-31 07:11:24

问题


i have a class representing cars:

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

and another class representing races:

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

Its my implementation to sorting the Set, i know there is a TreeSet but i dont know how to compare it by TreeSet instead of HashSet, because if i used TreeSet i couldnt find method comprator() in it, can anyone help me if im doing well or if not how to use TreeSet?


回答1:


Here's a snippet from the 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.

Natural ordering refers to the order that you enforced by making the Car class implement the Comparable interface. Just add your cars to the TreeSet instance and they will be sorted for you.




回答2:


Use a Comparator instead of Comparable in Car. Comparator is external to the class it compares, whereas Comparable is internal to that class. A more detailed explanation is here: https://stackoverflow.com/a/4108764/1838970

Now, on to your question. Implement this Comparator:

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

Now make a TreeSet using that Comparator:

Set<Car> cars = new TreeSet<Car>(new CarComparatorByName());

That TreeSet will now use the comparator you created.

Alternatively, as noted in the comments below, you could just keep Car as a Comparable and simply throw them into a TreeSet upon creation. That TreeSet will use the natural sort order defined in Car implements Comparable.



来源:https://stackoverflow.com/questions/22671315/best-way-to-sort-a-set

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!