I have a class which I want to set up as keys in HashMap. I already have implemented the compareTo method for that class. But still when I do:
map.put(new MyKey(dummyArguements) , dummyValue ); System.out.println(map.get( new MyKey(dummyArguements) ) );
I get null. So that means hashmap is not able to identify that the two keys (for get & put call) are same.
Could someone help me here please ?
Custom Key Classes We can conclude that to use a custom class for a key, it is necessary that hashCode() and equals() are implemented correctly. To put it simply, we have to ensure that the hashCode() method returns: the same value for the object as long as the state doesn't change (Internal Consistency)
If you want to make a mutable object as a key in the hashmap, then you have to make sure that the state change for the key object does not change the hashcode of the object. This can be done by overriding the hashCode() method. But, you must make sure you are honoring the contract with equals() also.
If we wish to create a HashMap of our own class, we need to ensure that the hashcode() of the key of HashMap doesn't change as if it happens then it is impossible to get object value of the key from HashMap. On runtime, JVM processes hash code for each object and give it on interest.
Therefore, to use an object as a key in HashMap , HashSet , or Hashtable in Java, we need to override equals and hashcode methods of that object since default implementation of these methods simply check for the instance equality.
You need to implement hashCode()
and equals()
. compareTo()
is additionally required for sorted map/set.
See this question for details.
You should implement equals()
and hashCode()
. Your class should also be immutable. If it is mutable, it's hash code can change after adding it to map. Then the map can have problems finding it.
1) In general for collections, what you want to override is the equals() method (and also the hashcode() method) for your class. compareTo()/Comparable and Comparator are typically used for sorting and only take the place of using the equals() method for object equivalance in some cases - examples are implementers of SortedSet such as TreeSet.
2) Please conform to Java naming standards in your code. Your class names should be capitalized... e.g new MyKey(dummyArguments)
. See http://www.oracle.com/technetwork/java/codeconventions-135099.html#367 (and http://www.oracle.com/technetwork/java/codeconvtoc-136057.html) for more detail.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With