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.
A
TreeSet
is a binary search tree, which is based on the notion that given two elements a and b, it is either the case that a is "smaller than" b, or not. However, if you define your own class, theTreeSet
doesn't know how to determine whether a given object of that class is "smaller than" another object because it can't know your intended interpretation of the objects' contents. Therefore, you can create aComparator
which can do the comparisons on behalf of theTreeSet
.It's used to sort the elements of the Set according to user-defined rules.
See the javadoc:
See here for more information on natural objects ordering.
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.
Treeset class has the below constructor so that Treeset stores the element using the in the order as described by the Comparator c.Below is an example to illustrate the same.
Here if you see the namecomp is implementing the Comparator interface and thus sorting the elements of the Employeee class in the descending order on the basis of the Name field. Now the Treeset is implementing the namecomp comparator to store the element in the descending order on the basis of the Name field. Output 2 1 3
Hope this answers the question.
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. For instance it may be on rollno, name, age or anything else.
By passing a Comparator in
TreeSet(Comparator<? super E> c)
it means that you can order your TreeSet based on the parameter you desire.Suppose you have
TreeSet<User>
and you have a User class with fieldid
in it.Now if you want to sort your TreeSet based on User id you can pass a Comparator object in your TreeSet to obtain the desired ordering.
TreeSet with default constructor will sort the element in natural ascending order, but if you want some custom sorting according to your requirement then you should go for the Comparator interface. eq This is your default class Employee and you want to sort this class according to salary then.
Here we have created another class by implementing Comparator.