Thursday, November 27, 2014

TreeSet in java : A detailed overview

2:48 PM

TreeSet in java under Collection Framework have below property.

1. Underlying data structure is balanced  tree.
2. Doesn't allow duplicate.
3. Elements are inserted as per natural sorting order by default.
4. All elements which are inserted as per default natural sorting order must be comparable in nature.
5. An object is said to be comparable only if corresponding class implements java.lang.Comparable interface.
6. If we use default natural sorting order than objects are compared using compareTo(Object obj) method of java.lang.Comparable interface.
7. Null insertion is not allowed.


Constructor in TreeSet

TreeSet ts=new TreeSet(); //creates an empty TreeSet with default natural sorting order
TreeSet ts=new TreeSet(Comparator c); //creates an empty TreeSet with passed Customoized sorting order

TreeSet ts=new TreeSet(SortedSet s); //Creates a TreeSet view of a Passed SortedSet argument object.


//TreeSetDemo.java


import java.util.*;
class TreeSetDemo 
{
 public static void main(String[] args) 
 {
  TreeSet ts=new TreeSet();
  ts.add("10");
  ts.add("20");
  ts.add("30");
  System.out.println(ts);
 }
}



TreeSet by default stores objects which are homogeneous and comparable, an object is said to be comparable if and only if it implements Comparable interface.

TreeSet stores elements based upon the default natural sorting order.Elements in the TreeSet are comparaed using compareTo(Object obj) method of java.lang.Comparable interface.

But if we want to store objects based upon our own customized sorting order then we need to have a class which implements java.util.Comparator interface.


Comparator


  • It is meant for customized sorting order.
  • Present in java.util package.
  • Contains below 2 method.

1. public int compare(Object obj1,Object obj2)
2. equals()


any class which implements java.util.Comparator Interface should compulsory implement compare() method. Whereas implementing equal() method is optional.

This is because every java class is a child class of Java.lang.Object class. Object class provide implementation for equals() method, so equals () is by default present in every java class.


Write a java program to insert Integer elements in TreeSet with desecending sorting order.



import java.util.*;
class ReverseTreeSet 
{
 public static void main(String[] args) 
 {
  TreeSet ts=new TreeSet(new Com());
  ts.add(10);
  ts.add(20);
  ts.add(30);
  ts.add(40);
  ts.add(50);
  System.out.println(ts);
 }
}

//Java code for customized sorting order


import java.util.*;
class Com implements Comparator
{
 public int compare(Object obj1, Object obj2)
 {
  Integer i1=(Integer)obj1;
  Integer i2=(Integer)obj2;
  return i2.compareTo(i1);
 }
}

0 comments :

Post a Comment

 

© 2014 DieHardTechy . All rights resevered. Designed by Diehardtechy