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.
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.