TreeSet in java


In this post, we will see TreeSet in java.
Java TreeSet have following properties:

  • It can contain only unique element.
  • It stores objects in ascending order by default,
  • It implements NavigableSet interface which extends SortedSet.
  • When you put objects in TreeSet, it must implement Comparable interface.

Lets understand it more with the help of example.


1) create a class named

2) create as below:

When you run above program, you get below out:

As you can see, we have added 6 country objects in Treeset but we have only 4!!. As TreeSet can only have unique elements,indiaCountry2 and nepalCountry2 did not add to the TreeSet. Explanation:

When you will put indiaCountry2 in treeSet it will compare this object with indiaCountry as indiaCountry2.compareTo(indiaCountry) and compareTo method will return 0. Both object will treated as equal. As you can not add duplicate element in TreeSet, indiaCountry2 will not be added to above TreeSet.

Now put debug point at line 27 and right click on project->debug as-> java application. Program will stop execution at line 27 then right click on countryTreeSet then select watch.You will be able to see structure as below.

TreeSet in java

Tricky question on TreeSet: 

Guess output of below program:

What will be output of above program:
A. Martin
B. John
C. John
D. Compilation fails.
E. The code runs with no output.
F. An exception is thrown at runtime.

Correct Answer is B here.


As you can see we have overridden compareTo method in Employee class and always return 0.
Following steps will take place:

  • First element with “John” will be added to employeeSet.
  • When we will added second element with martin, compareTo method will get called with employeeOne.compareTo(employeeTwo) and it will return 0.
  • As compareTo method returns 0, employeeOne is equals to employeeTwo, so employeeTwo will not be added to treeSet.
  • So output of above program is “John”
Please go through java interview programs for more such programs.

Related posts

Add Comment