Which is the output of this code?
A) Bart
Homer
Lisa
Maggie
Marge
B) Maggie
Bart
Lisa
Marge
Homer
C) Marge
Maggie
Lisa
Homer
Bart
D) Indeterminate
TreeSet and reverse()
Looking at the code, the first thing you should notice is that we’re using a TreeSet
, so the elements will be sorted automatically. The second thing is that the order of comparison is inverted, so the sorting will be done in reverse order.
When we first add elements into the list, TreeSet
automatically sorts them to:
Marge
Maggie
Lisa
Homer
Bart
Then we use the reverse()
method, which reverses the order of elements. So the final output would be:
Bart
Homer
Lisa
Maggie
Marge
Common mistakes with Comparable
- Trying to sort a non-comparable object in the
sort()
method. - Using
Comparable
for different sorting strategies within the same object. - Inverting comparison in the
compareTo()
method so that sorting will be in reverse order, like so:
Normal order:
Inverted order:public int compareTo(Simpson simpson) { this.name.compareTo(simpson.name); }
public int compareTo(Simpson simpson) { simpson.name.compareTo(this.name); }
- Adding a non-comparable (any object that doesn’t implement
Comparable
) object in aTreeSet
orTreeMap
object.
What to remember about sorting with Java
- Use
Comparable
when the comparison is standard for the given class. - Use
Comparator
when you need more flexibility. - It’s possible to use lambdas with
Comparator
. - Many Java core classes implement
Comparable
. - Use
TreeMap
orTreeSet
when sorting aMap
or aSet
. - The
compareTo()
method works with bothComparable
andComparator
. - The
compareTo()
method will return a positive number if one object is greater than the other, negative if it’s lower, and zero if they are the same.
Learn Java
- Sort it out: Learn more about sorting algorithms and how they work with the
Comparable
andComparator
interfaces in Java. - Go deeper with anonymous inner classes, lambda expressions, and other functional programming techniques in Java.
- Challenge yourself! Read all of Rafael's posts in the Java Challengers blog.
- Ready for a Java workout? Visit the Oracle Java Dev Gym.
- Just for fun: Check out Timo Bingmann's "Visualization and 'audibilization' of 15 sorting algorithms in 6 minutes."