Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TreeSet constructor with Comparator<?> parameter

Tags:

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.

like image 294
TheRapture87 Avatar asked Apr 17 '15 12:04

TheRapture87


People also ask

Can we use comparator with TreeSet?

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.

What is significance of using comparator interface while creating a TreeSet class object?

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.

Which constructor of TreeSet gives natural sorting order?

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.


1 Answers

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.

like image 113
Eran Avatar answered Oct 03 '22 23:10

Eran