Saturday 19 April 2014

TreeSet()

TreeSet is backed up by TreeMap. The implementation looks like below.

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

Constructs a new, empty tree set, sorted according to the natural ordering of its elements. TreeSet internally uses TreeMap, which stored the data in Red Black tree. So to comapre the data it uses the comapreTo method.

Example
import java.util.*;

class TreeSetConstructor1{
 public static void main(String args[]){
  TreeSet<Integer> mySet = new TreeSet<> ();
  
  /* Add Data to mySet */
  mySet.add(10);
  mySet.add(20);
  mySet.add(30);
  mySet.add(40);
  
  System.out.println("Elements in mySet are");
  System.out.println(mySet);
 }
}

Output
Elements in mySet are
[10, 20, 30, 40]

1. Any type of data insert into Tree set must implement Comparable interface, other wise ClassCastException thrown.

class Employee{
 int number;
 
 Employee(int number){
  this.number = number;
 } 
 
 public String toString(){
  return "Employee " + number;
 }
 
}

import java.util.*;

class TreeSetConstructor1Ex{
 public static void main(String args[]){
  TreeSet<Employee> mySet = new TreeSet<> ();
  
  Employee e1 = new Employee(1);
  Employee e2 = new Employee(2);
  
  /* Add Data to mySet */
  mySet.add(e1);
  mySet.add(e2);
  
  System.out.println(mySet);
 }
}

Output
Exception in thread "main" java.lang.ClassCastException: Employee cannot be cast
 to java.lang.Comparable
        at java.util.TreeMap.compare(TreeMap.java:1188)
        at java.util.TreeMap.put(TreeMap.java:531)
        at java.util.TreeSet.add(TreeSet.java:255)
        at TreeSetConstructor1Ex.main(TreeSetConstructor1Ex.java:11)

To make the program Exception free, Employee class must implement the Comparable interface.

class Employee implements Comparable{
 Integer number;
 
 Employee(int number){
  this.number = number;
 } 
 
 public String toString(){
  return "Employee " + number;
 }
 
 public int compareTo(Object obj){
  if(obj == null)
   throw new NullPointerException();
  if(!(obj instanceof Employee))
   throw new IllegalArgumentException();
   
  Employee e1 = (Employee) obj;
  
  return this.number.compareTo(e1.number);
 }
}

Output
[Employee 1, Employee 2]








Prevoius                                                 Next                                                 Home

No comments:

Post a Comment