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.
TreeSet shares an important function of setting and returning the comparator that can be used to order the elements in a TreeSet. The method returns a Null value if the set follows the natural ordering pattern of the elements.
Comparator interface is used to order the objects of user-defined class. It provides multiple sorting sequence i.e. you can sort the elements based on any data member.
TreeSet(SortedSet): This constructor is used to build a TreeSet object containing all the elements from the given sortedset in which elements will get stored in default natural sorting order.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With