Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
An element in a list can compare itself to another of its own type in only one way, using its compareTo() method. But a Comparator is external to the element type you’re comparing—it’s a separate class. So you can make as many of these as you like! Want to compare songs by artist? Make an ArtistComparator. Sort by beats per minute? Make a BPMComparator.
If you pass a Comparator to the sort() method, the sort order is determined by the Comparator rather than the element’s own compareTo() method.
Then all you need to do is call the overloaded sort() method that takes the List and the Comparator that will help the sort() method put things in order.
The sort() method that takes a Comparator will use the Comparator instead of the element’s own compareTo() method, when it puts the elements in order. In other words, if your sort() method gets a Comparator, it won’t even call the compareTo() method of the elements in the list. The sort() method will instead invoke the compare() method on the Comparator.