Sort and equals()

The two static sorting methods of the Collections class are:

  • void sort(List<T> list)
  • void sort(List<T> list, Comparator<T> comparator)

The first sort(List<T>) method accepts only lists with elements that implement the Comparable interface, which requires implementation of the compareTo(T) method. The order established by the compareTo(T) method implemented by each element is called natural ordering.

The second sort() method does not require the list elements to implement any particular interface. It uses the passed-in object of the class Comparator to establish the required order using the Comparator.compare(T o1, T o2) methodIf the elements of the list implement Comparable, then their method compareTo(T) is ignored ...

Get Introduction to Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.