I would like to know what it means when javadocs for TreeSet
says
This class implements the Set interface, backed by a TreeMap instance?
In the below example, I haven't implemented the Hashcode
method and still it is working as per expectation i.e it is able to sort the objects. Notice that I have purposely not implemented a consistent Equals
implementation to check the TreeSet
behaviour.
import java.util.TreeSet;
public class ComparisonLogic implements Comparable<ComparisonLogic>{
String field1;
String field2;
public String toString(){
return field1+" "+field2;
}
ComparisonLogic(String field1,String field2){
this.field1= field1;
this.field2= field2;
}
public boolean equal(Object arg0){
ComparisonLogic obj = (ComparisonLogic) arg0;
if(this.field1.equals(obj.field1))
return true;
else
return false;
}
public int compareTo(ComparisonLogic arg0){
ComparisonLogic obj = (ComparisonLogic) arg0;
return this.field2.compareToIgnoreCase(obj.field2);
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ComparisonLogic x = new ComparisonLogic("Tom", "jon");
ComparisonLogic y = new ComparisonLogic("Tom", "Ben");
ComparisonLogic z = new ComparisonLogic("Tom", "Wik");
TreeSet<ComparisonLogic> set = new TreeSet<ComparisonLogic>();
set.add(x);
set.add(y);
set.add(z);
System.out.println(set);
}
}
This example prints [Tom Ben, Tom jon, Tom Wik]
. So it is sorting based on the compareTo
method and hashcode()
method looks insignificant in this scenario. However, Treeset
is backed by TreeMap, so internally if TreeMap
is used for sorting, how is TreeMap
hashing the object?