Reputation: 289
I have a map that uses a class I have created as keys. The class overrides both the equals and compareTo methods. Can someone explain specifically how Hashmap.get(key) and TreeMap.get(key) use these methods?
Upvotes: 0
Views: 1060
Reputation: 1685
Hashmap.get(key) results in calling of hashcode of the key object and after deciding the bucket by using the hashcode then the equals is called on the key to determine the value of the key.
TreeMap is an implementation of SortedMap which means that objects stored as key in the treemap should implement Comparable interace if not then we need to send a Comparator<T>
(where T is the key class) object to the constructor of TreeMap. Reason for this is the keys are sorted . To sort JVM needs to know how to compare and hence this restriction If your key class implements Comparable interface then the compareTo method implementation of this interface is called . There is a binding contract here which states that the compareTo and equals method of key class should be compatible which means compareTo should retun 0 and equals should return true for two equal key objects so that your TreeMap key will be unique.
In short,
HashMap.get(key) calls hashCode method of key and then calls equals method of key
TreeMap.get(key) calls the compareTo method of your key class or calls the compare method of the Comparator object that you would have passed to the constructor of TreeMap
Upvotes: 2