This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
The JavaDocs do this, backed up by the Collections framework tutorial. Rather than rehash what is written there can you explain what it is you don't understand? Are you wondering why there are two simmilar interfaces? Or how to use them?
In the real business world, there are many cases where we're required to perform sorting on a Collection of some user-defined objects. If the element of the Collection is a String type, or any other class which implements Comparable, then the sorting can be performed in the natural order. But sometimes, we want to perform a different criteria for sorting, or probably we want to sort a user-defined type.
Here's where Comparator comes into play. Clean and extensible.
Here's an example of a simplified user-defined type:
In the above class, the most commonly found as natural ordering would be order by lastName. This can easily be implemented using the Comparable interface, i.e.
Sorting a List of Customer objects would be as simple as:
But, if we want to use a different ordering, e.g. order by the first name, then we cannot use the natural ordering as defined within the Customer class. Instead, we have to define an alternative ordering, in the form of a Comparator class.
Sorting a List of Customer objects by their first name, would be:
// assuming you implement singleton..
Comparator comparator =
Collections.sort (customerList, comparator);
Simple, clean & extensible. You can start defining more and more Comparator classes to suit your needs. As it is a Java class, you can also perform complex comparison on the objects.