TreeSet Class

TreeSet

  • The underlying data structure is balanced tree.
  • Duplicate objects are not allowed.
  • Insertion order is not preserved and it is based on some sorting order of objects.
  • Heterogeneous objects are not allowed if we are trying to insert heterogeneous objects then we will get ClassCastException.
  • Null insertion is possible(only once).
Constructors

TreeSet t=new TreeSet();

Creates an empty TreeSet object where all elements will be inserted according to default natural sorting order.

TreeSet t=new TreeSet(Comparator c);

Creates an empty TreeSet object where all objects will be inserted according to customized sorting order specified by Comparator object.

TreeSet t=new TreeSet(SortedSet s);

TreeSet t=new TreeSet(Collection c);

package com.ashok.collections;

import java.util.TreeSet;

public class MyTreeSet {
   public static void main(String args[]) {
      // TreeSet of String Type
      TreeSet tset = new TreeSet();
      // Adding elements to TreeSet
      tset.add("Ashok");
      tset.add("Vinod");
      tset.add("Dillesh");
      tset.add("Thiru");
      tset.add("Mahesh");
      tset.add("Janaki");

      // Displaying TreeSet
      System.out.println(tset);
      
     // TreeSet of Integer Type
     TreeSet tset2 = new TreeSet();
     // Adding elements to TreeSet
     tset2.add(88);
     tset2.add(7);
     tset2.add(101);
     tset2.add(0);
     tset2.add(3);
     tset2.add(222);
     System.out.println(tset2);
   }
}
null Acceptance

For the empty TreeSet as the first element null insertion is possible. But after inserting null if we are trying to insert any other element we will get NullPointerException.

If the TreeSet already contains some elements if we are trying to insert null we will get NullPointerException.

import java.util.*;

class TreeSetDemo {
   public static void main(String arg[]) {
      TreeSet tset = new TreeSet();
      tset.add(new StringBuffer("A"));
      tset.add(new StringBuffer("B"));
      tset.add(new StringBuffer("T"));
      tset.add(new StringBuffer("Z"));
      System.out.println(tset);
   }
}
Output
R.E: ClassCastException

Note

  • Exception in thread “main” java.lang.ClassCastException: java.lang.StringBuffer cannot be cast to java.lang.Comparable
  • If we are depending on natural sorting order compulsory the objects should be homogeneous and comparable other wise we will get class cast Exception.
  • An object is said to be comparable(if and only if) the corresponding class has to implement comparable interface.
  • All wrapper classes and String class already implemented comparable interface. But the String buffer doesn’t implement comparable interface. Hence in the above program we got class cast exception.
TreeSet Class
Scroll to top