Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

16. Collections and Generics: Data structures > Using a custom Comparator

Using a custom Comparator

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.

image with no caption

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.


  

You are currently reading a PREVIEW of this book.

                                                                                        

Get instant access to over
$1 million worth of books and videos.

  

Start a Free Trial