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

1 comment: