TreeSet constructor with Comparator<?> parameter

TheRapture87 picture TheRapture87 · Apr 17, 2015 · Viewed 51.6k times · Source

In Java’s documentation for its class TreeSet one of the constructors is shown to have the following header:

TreeSet(Comparator<? super E> c)

Can someone help explain why there is a constructor for TreeSet which takes a comparator object as its argument? I have no clue why this is done.

Answer

Eran picture Eran · Apr 17, 2015

The elements in a TreeSet are kept sorted.

If you use a constructor that has no Comparator, the natural ordering of the element class (defined by the implementation of Comparable) would be used to sort the elements of the TreeSet.

If you want a different ordering, you supply a Comparator in the constructor.