OK I understand the working of equals and hashcode and How they are used in hashmap. But This question crossed my mind What if I am having a third party object which does'nt have overridden hashcode and equals and I am not even allowed to modify it.
Consider following Class:
//Unmodifiable class
public final class WannaBeKey{
private String id;
private String keyName;
//Can be many more fields
public String getId()
{
return id;
}
public String getKeyName()
{
return id;
}
//no hashcode or equals :(
}
Now I want to make this class as my Hashmap key obviously it won't work without equals and hashcode. I want to know is there any way to handle such cases? I am unable to think of any or I am way over my head..
Thanks.
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)
The Map object holds key-value pairs and remembers the original insertion order of the keys. Any value (both objects and primitive values) may be used as either a key or a value.
The short answer is "no". All JavaScript object keys are strings. Even if you pass an object as a key, the object's toString() will be called on it, and the key will be stringified to [object Object] .
In order to use any object as Key in HashMap, it must implements equals and hashcode method in Java.
I've encountered this previously, and worked around it by creating a wrapper for the WannaBeKey as such:
public class WannaBeKeyWrapper {
private final WannaBeKey key;
public WannaBeKeyWrapper(WannaBeKey key) {
this.key = key;
}
public boolean equals(Object obj) {
// Insert equality based on WannaBeKey
}
public int hashCode() {
// Insert custom hashcode in accordance with http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#hashCode()
}
}
Obviously this changes your Set
from Set<WannaBeKey>
to Set<WannaBeKeyWrapper>
, but you should be able to account for that.
You can create a wrapper for that object which will have the overridden methods. Then you can use the wrapper class as the key of your hash map.
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