Constructors and methods of TreeSet in Java

There are four constructors defined for TreeSet.

  • TreeSet()
  • TreeSet(Collection c)
  • TreeSet(Comparator comparator)
  • TreeSet(SortedSet sortedSet)

TreeSet() – This is default constructor which is used to create new and empty TreeSet, sort the added elements in ascending order. Intrnally this constructor uses TreeMap. Let’s see internal code of this constructor.

 
public TreeSet() {
        this(new TreeMap<E,Object>());
    }

Example 1 –

package treeset;

import java.util.Set;
import java.util.TreeSet;

public class TreeSetExample {
	public static void main(String[] args) {
		
		//TreeSet Object using default constructor
		Set<String> treeSetObj = new TreeSet<>();
		treeSetObj.add("ram");
		treeSetObj.add("mohan");
		treeSetObj.add("sohan");
		treeSetObj.add("rohan");
		System.out.println(treeSetObj);

	}
}

Output is – [mohan, ram, rohan, sohan]

Example 2 – What will happen if we try to add different types of elements in TreeSet. For example, we will not define the generic type, can we add String as well as Integer? In the case of ArrayList, we can do no problem, what will happen in case of TreeSet. Let’s see an example, first we will see an example for ArrayList then TreeSet.

Adding heterogeneous elements in ArrayList –

import java.util.ArrayList;

public class ArrayListDiffTypeElemt {
	public static void main(String[] args) {
		
		//As of now we are not defining generic type
		//Always remember in real time development 
		//we avoid to create object this way
		//we use generic
		
		ArrayList arrayListObj = new ArrayList();
		arrayListObj.add("ram");
		arrayListObj.add(10);
		arrayListObj.add(10.0f);
		System.out.println(arrayListObj);

	}
}

Output is – [ram, 10, 10.0]

In the case of ArrayList, we can have different types of elements.

Adding heterogeneous elements in TreeSet – At compile time there is no issue, but while running this program we will get ClassCastException.

import java.util.TreeSet;

public class TrreSetDiffTypeElemt {
	public static void main(String[] args) {

		// As of now we are not defining generic type
		// Always remember in real time development
		// we avoid to create object this way
		// we use generic

		TreeSet treeSetObj = new TreeSet();
		treeSetObj.add("ram");
		treeSetObj.add(10);
		treeSetObj.add(10.0f);
		System.out.println(treeSetObj);

	}
}

Output is –


Exception in thread “main” java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
at java.lang.Integer.compareTo(Unknown Source)
at java.util.TreeMap.put(Unknown Source)
at java.util.TreeSet.add(Unknown Source)
at ArrayListDiffTypeElemt.main(ArrayListDiffTypeElemt.java:13)

Now question aries why we gettig this exception in case of TreeSet, internally TreeSet try to sort the elements, for sorting it uses compareTo() method. As soon as it finds differnets types of elements it thorws ClassCastException.

 

TreeSet(Collection c) – We can pass any type of collection classes which implements Collections interface and can convert it into TreeSet. For example, we are going to convert ArrayList into TreeSet in below example before that let’s see how this constructor has been defined in TreeSet class.


Internal implementation –

public TreeSet(Collection<? extends E> c) {
        this();
        addAll(c);
    }

Example –

package treeset;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class TreeSetConstructorExap2 {
	public static void main(String[] args) {

		// Create a new TreeSet from different other collection classes
		// Here we will create TreeSet from ArrayList
		List<String> listObject = new ArrayList<>();

		listObject.add("ram");
		listObject.add("mohan");
		listObject.add("shyam");
		listObject.add("mohan");
		listObject.add("ram");
		System.out.println("before converting intp treeset-- " + listObject);

		// we have constructor TreeSet(Collection c), which can take any type
		// class as parameter which implements Collection interface
		Set<String> treeSetObj = new TreeSet<>(listObject);
		System.out.println("After converting into treeset-- " + treeSetObj);

	}
}

Output is –

before converting intp treeset– [ram, mohan, shyam, mohan, ram]
After converting into treeset– [shyam, mohan, ram]

 

TreeSet(Comparator comparator) – We can pass any class object which implements  Comparator interface.

Internal implementation –

 public TreeSet(Comparator<? super E> comparator) {
        this(new TreeMap<>(comparator));
    }

Example –

package treeset;

import java.text.Collator;
import java.util.Set;
import java.util.TreeSet;

public class TreeSetConstructorExap3 {
	public static void main(String[] args) {

		// Here we have Collator class which implements Comparator interface
		Collator myCollator = Collator.getInstance();
		
		//we have TreeSet constructor which can take Comparator 
		//below we are passing  myCollator object which internally 
		// implements Comparator interface
		Set<String> treeSetObj = new TreeSet<>(myCollator);
		treeSetObj.add("ram");
		treeSetObj.add("mohan");
		treeSetObj.add("sohan");
		treeSetObj.add("rohan");
		treeSetObj.add("ram");
		for (String str : treeSetObj) {
			System.out.println(str);
		}
	}
}

Output is –

mohan
ram
rohan
sohan


 

TreeSet(SortedSet sortedSet) – 

Internal implementation –

 public TreeSet(SortedSet s) {
        this(s.comparator());
        addAll(s);
    }

Example –

package treeset;

import java.util.Set;
import java.util.TreeSet;

public class TreeSetConstructorExap4 {
	public static void main(String[] args) {

		Set<String> treeSetObj = new TreeSet<>();
		treeSetObj.add("ram");
		treeSetObj.add("mohan");
		treeSetObj.add("sohan");
		treeSetObj.add("rohan");
		treeSetObj.add("ram");

		// we have a constructor which can takes class object as parameter which
		// implements
		// SortedSet. Since TreeSet implements SortedSet interface we can pass
		// TreeSet itself. Although this doesn't make any sense but for
		// learning purpose we doing
		Set<String> treeSetObj1 = new TreeSet<String>(treeSetObj);

		for (String str : treeSetObj1) {
			System.out.println(str);
		}
	}
}

Output is –

mohan
ram
rohan
sohan