I was testing the behaviour of TreeMap
and understood the process of sorting. However I am still in the confusing thought that, for retrieval does the custom key class needs to override the hashCode method. Having said that, I have searched enough of google but could not find any justifiable answer.
Below is the example which I worked with.
class Dog implements Comparable<Dog> {
String color;
int size;
Dog(String c, int s) {
color = c;
size = s;
}
int hc;
@Override
public int hashCode() {
hc = super.hashCode();
return hc;
}
@Override
public int compareTo(Dog o) {
return this.color.compareTo(o.color);
}
}
Test Code for testing the TreeMap..
public class TestHashMap {
public static void main(String[] args) {
Dog d1 = new Dog("a", 1);
Dog d2 = new Dog("b", 2);
Dog d3 = new Dog("c", 3);
Dog d4 = new Dog("d", 4);
Dog d5 = new Dog("e", 5);
Dog d = new Dog("c", 3);
TreeMap<Dog, Integer> hm = new TreeMap<>();
hm.put(d1, 10);
hm.put(d2, 15);
hm.put(d3, 5);
hm.put(d4, 20);
hm.put(d5, 25);
System.out.println("value is :" + hm.get(d));
}
}
Irrespective of I implement hashCode method or not the value is retrieved correctly, However when debugging , always hashcode method is called , so I am confused if really hashCode implementation is mandatory.
Could anybody please help in understanding the correct behaviour of retrieval from TreeMap.
Please do not copy paste java doc from TreeMap.
The hashCode()
is called as a part of default toString()
implementation. Since you haven't implemented your own toString()
, I'd suspect you printed a Dog
somewhere in your code which caused the method invocation.