TreeSet

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

Constructors:
1) TreeSet t = new TreeSet();
• Creates an empty TreeSet object where all elements will be inserted according to default natural sorting order.
2) 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.
3) TreeSet t = new TreeSet(SortedSet s);
4) TreeSet t = new TreeSet(Collection c);

Example 1:
import java.util.*;
class TreeSetDemo
{
public static void main(String[] args)
{
TreeSet t = new TreeSet();
t.add(“A”);
t.add(“a”);
t.add(“B”);
t.add(“Z”);
t.add(“L”);
//t.add(new Integer(10));//ClassCastException
//t.add(null);//NullPointerException
System.out.println(t);//[A, B, L, Z, a]
}
}
Null acceptance:
• For the empty TreeSet as the 1st element “null” insertion is possible but after inserting that null if we are trying to insert any other we will get NullPointerException.
• For the non empty TreeSet if we are trying to insert null then we will get NullPointerException.

Example 2:
import java.util.*;
class TreeSetDemo
{
public static void main(String[] args)
{
TreeSet t = new TreeSet();
t.add(new StringBuffer(“A”));
t.add(new StringBuffer(“Z”));
t.add(new StringBuffer(“L”));
t.add(new StringBuffer(“B”));
System.out.println(t);
}
}
Output:-
Runtime Exception.
• Exception in thread “main” java.lang.ClassCastException: java.lang.StringBuffercannot be cast to java.lang.Comparable

• If we are depending on default natural sorting order compulsory the objects should be homogeneous and Comparable otherwise we will get ClassCastException.
• An object is said to be Comparable if and only if the corresponding class implements Comparable interface.
• String class and all wrapper classes implements Comparable interface but StringBufferclass doesn’t implement Comparable interface hence in the above program we are getting ClassCastException.

Leave a Reply

Your email address will not be published. Required fields are marked *