JAVA TECH

Saturday, 28 May 2011

Difference between TreeSet And HashSet

TreeSet internally uses the compare to check dulicate and HashSet internally use the hashCode() and equals().
The below Example shows the difference--


import java.util.HashSet;
import java.util.TreeSet;

public class Test {
public static void main(String[] args) {
HashSet hashSet=new HashSet();
TreeSet
treeSet=new TreeSet();
A a1=new A();
a1.setI(1);
A a2=new A();
a2.setI(1);
hashSet.add(a1);
hashSet.add(a2);
treeSet.add(a1);
treeSet.add(a2);
System.out.println("Size of HashSet is "+ hashSet.size());
System.out.println("Size of TreeSet is "+ treeSet.size());

}
}





class A implements Comparable
{
private int i;

public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
}
@Override
public boolean equals(Object o) {
if(o instanceof A){
A a=(A)o;
return a.i==this.i;
}else
return false;
}
@Override
public int hashCode() {
return i;
}
public int compareTo(A o) {

return 1;
}

}

OutPut will be:
Size of HashSet is 1
Size of TreeSet is 2
Posted by Vishnu Agarwal at 10:47 am No comments:
Email ThisBlogThis!Share to XShare to FacebookShare to Pinterest
Newer Posts Older Posts Home
Subscribe to: Posts (Atom)

Blog Archive

  • ►  2016 (3)
    • ►  June (1)
    • ►  January (2)
  • ►  2015 (23)
    • ►  December (1)
    • ►  September (1)
    • ►  August (9)
    • ►  July (11)
    • ►  June (1)
  • ►  2014 (1)
    • ►  January (1)
  • ►  2012 (8)
    • ►  October (2)
    • ►  September (1)
    • ►  June (2)
    • ►  May (2)
    • ►  April (1)
  • ▼  2011 (7)
    • ►  December (1)
    • ►  July (2)
    • ►  June (1)
    • ▼  May (1)
      • Difference between TreeSet And HashSet
    • ►  January (2)
  • ►  2010 (2)
    • ►  June (2)

Search This Blog

Followers

JavaTech. Awesome Inc. theme. Powered by Blogger.