Sunday, October 20, 2013

TreeSet concepts

When to choose TreeSet ?

 If you want to store the objects in sorted order then choose TreeSet.

Example:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package corejava;

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

/**
 *
 * @author Rishitha
 */
public class TreeSetEx {
   
    public static void main(String args[]){
       
        Set<String> tSet = new TreeSet<String>();
        tSet.add("Boat");
        tSet.add("Home");
        tSet.add("Apple");
       
       
        for(String s:tSet){
           
            System.out.println(s);
        }
  }
}

Output:
--------

Apple
Boat
Home

Very important things to learn about TreeSet:

Suppose we have a class Student with
a)sid
b)sname

If we add the student objects to treeset and run we will get big exception.
Run the code given after this exception.
When we added string objects there is no problem but when you add userdefinedclass
objects you are getting exception..

Exception in thread "main" java.lang.ClassCastException: corejava.StudentClass 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 corejava.TreeSetEx.main(TreeSetEx.java:28)

Why it is throwing exception when I am adding StudentClass objects ?
-----------------------------------------------------------------------
Because... We are asking treeset to sort... but treeset is in dilemma
1)Do I need to sort... the StudentClass objects based on sid
or
2)Do I need to sort.. the studentClass objects based on sname....

So.. we need to let Treeset know... how to sort ?
---------------------------------------------------

Ok.... But still you would have a question why exception didn't occur when I added
String objects in to Treeset.

Answer ?
-----------
It is because String class implemented... Comparable Interface and overridden the
compareTo method.

compareTo is the way you can tell the treeset how to sort...the objects you have
added in to TreeSet.

So.. we need to override the comparetTo in StudentClass and TreeSet can take
the help of compareTo in your StudentClass and sorts the objects..

You have to override the compareTo as following to sort objects based
on sid.
If compareTo returns 0 then 2 students need to be considered equal.
If  we return negative Integer then This student is < the student passed as
argument to compareTo
If we return postive integer then This student is > the student passed as
argument to compareTo

public int compareTo(Object o) {
        StudentClass sec = (StudentClass)o;
        if(this.sid == sec.sid) return 0;
        else if(this.sid < sec.sid){
            return -1;
        }else{
            return 1;
        }
       
    }





/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package corejava;

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

/**
 *
 * @author Rishitha
 */
public class TreeSetEx {
   
    public static void main(String args[]){
       
        Set<StudentClass> tSet = new TreeSet<StudentClass>();
      
        StudentClass one = new StudentClass();
        one.setSid(1);
        one.setSname("FirstStudent");
       
        StudentClass two = new StudentClass();

        two.setSid(2);
        two.setSname("SecondStudent");
        tSet.add(one);
        tSet.add(two);
       
   }

}


***************************
So the Correct way to sort UserDefinedClass is as follows

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package corejava;

/**
 *
 * @author Rishitha
 */
 class StudentClass implements Comparable{
    int sid;
    String sname;

    public int getSid() {
        return sid;
    }

    public void setSid(int sid) {
        this.sid = sid;
    }

    public String getSname() {
        return sname;
    }

    public void setSname(String sname) {
        this.sname = sname;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final StudentClass other = (StudentClass) obj;
        if (this.sid != other.sid) {
            return false;
        }
        return true;
    }

  

    @Override
    public int hashCode() {
        int hash = 5;
        return hash;
    }

    @Override
    public int compareTo(Object o) {
        StudentClass sec = (StudentClass)o;
        if(this.sid == sec.sid) return 0;
        else if(this.sid < sec.sid){
            return -1;
        }else{
            return 1;
        }
       
    }

    @Override
    public String toString() {
        return "StudentClass{" + "sid=" + sid + ", sname=" + sname + '}';
    }
   
   
   
   
}


TreeSetEx.java

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package corejava;

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

/**
 *
 * @author Rishitha
 */
public class TreeSetEx {
   
    public static void main(String args[]){
       
        Set<StudentClass> tSet = new TreeSet<StudentClass>();
      
        StudentClass one = new StudentClass();
        one.setSid(1);
        one.setSname("FirstStudent");
       
        StudentClass two = new StudentClass();

        two.setSid(2);
        two.setSname("SecondStudent");
        tSet.add(one);
        tSet.add(two);
       
        for(StudentClass s:tSet){
            System.out.println(s);
        }
       
       
      
    }
   
   
   
   
}






















No comments:

Post a Comment