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.

Example:

1) create a class named Country.java.
package com.org.arpit.java2blog;
public class Country implements Comparable{

    String countryName;

    public Country(String countryName) {
        super();   
        this.countryName = countryName;
    }

    @Override
    public int compareTo(Object arg0) {
        Country country=(Country) arg0;
        
        return (this.countryName.compareTo(country.countryName) ) ;
    }
    
    public String getCountryName() {
        return countryName;
    }

    public void setCountryName(String countryName) {
        this.countryName = countryName;
    }

}

2) create TreeSetMain.java as below:
package com.org.arpit.java2blog;

import java.util.Iterator;
import java.util.TreeSet;

public class TreeSetMain {

 /**
  * @author Arpit Mandliya
  */
 public static void main(String[] args) {
  Country indiaCountry=new Country("India");
  Country chinaCountry=new Country("China");
  Country nepalCountry=new Country("Nepal");
  Country bhutanCountry=new Country("Bhutan");
  Country indiaCountry2=new Country("India");
  Country nepalCountry2=new Country("Nepal");

  TreeSet<country> countryTreeSet = new TreeSet<country>();
  countryTreeSet.add(indiaCountry);
  countryTreeSet.add(chinaCountry);
  countryTreeSet.add(nepalCountry);
  countryTreeSet.add(bhutanCountry);
  countryTreeSet.add(indiaCountry2);
  countryTreeSet.add(nepalCountry2);

  Iterator<country> counIter=countryTreeSet.iterator(); // put debug point here
  while(counIter.hasNext())
  {
   System.out.println(counIter.next().countryName);
  }
 }

}
When you run above program, you get below out:
Bhutan
China
India
Nepal
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-&gt;debug as-&gt; 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:
package com.org.arpit.java2blog;
import java.util.Iterator;
import java.util.TreeSet;
public class Employee implements Comparable { 
 public String name;
 public int compareTo(Object o) {
  return 0;
 }
 public static void main(String args [])
 {
  Employee employeeOne = new Employee();
  Employee employeeTwo = new Employee();
  employeeOne.name= "John";
  employeeTwo.name= "Martin";
  TreeSet<Employee> employeeSet = new TreeSet<Employee>();
  employeeSet.add(employeeOne);
  employeeSet.add(employeeTwo);
  Iterator<Employee> empIt=employeeSet.iterator();
  while(empIt.hasNext())
  {
   System.out.println(empIt.next().name);
  } 
 }
}

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

Correct Answer is B here.

Explanation:

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.

Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus

 

Java tutorial for beginners Copyright © 2012