Task 5 of 7 · 0 solved · 7 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

8.2 Comparable — a different order with Comparator

Lesson

Один класс — один естественный порядок

Comparable gives a class one natural order: students by score. But sometimes you need another — the same students by name. Editing the class is wrong: the natural order is still by score, you just want a different sort this time.

That is what Comparator is for: a separate object holding an order, passed to sort as a second argument.


Worked example

Collections.sort(list, new Comparator<Student>() {
    public int compare(Student p, Student q) {
        return p.getName().compareTo(q.getName());
    }
});

Two interfaces, one job, different placement. Comparable is implemented by the class and answers «how do I compare to another?». Comparator is a separate object and answers «how do I compare these two?». One class can be sorted by any number of Comparators without being touched.


▶ Try it: run this, then change something and run it again.



Comparator differs from Comparable because it is...


How many Comparators can one class have?


To sort by an order other than the natural one, you pass...


The method a Comparator must provide is called...


True or false?