I am stuck around while studying hashCode() in java. I wrote a sample code PFB snippet
public class Shared {
String type;
Date date;
public Shared(String type) {
this.type = type;
}
public void setType(String type) {
this.type = type;
this.date = new Date(19894894823948L);
}
public static void main(String arg[]) {
HashMap<Shared, String> hm = new HashMap<Shared, String>();
Shared key = new Shared("me");
Shared key1 = new Shared("me1");
hm.put(key1, "value1");
hm.put(key, "value");
System.out.println(key.hashCode());//returning hashcode suppose X
key.type=null;
key.setType("type");
System.out.println(key.hashCode());// it's even returning X again
key.type="null";
System.out.println(key.hashCode());// it's even returning X again.
}
I am really confused how this is possible even after changing the value contained within the key hashCode is same. it's literally breaking the immutable key concept.
Is the hashCode() method architecture/platform dependent?
I am really confused how this is possible even after changing the value contained within the key hashCode is same. it's literally breaking the immutable key concept.
Nope, it's fine. You're not overriding equals
or hashCode
, so it's not using the value of the type
field as part of the equality comparison... it's just using reference identity, effectively. key
still refers to the same object as it did, so it's entirely sensible for it to return the same hash code. Nothing affecting the hash code or equality has changed.
If you want your Shared
type to be useful as a key in a map, I'd suggest:
hashCode()
and equals()
, making sure you obey all the relevant contractsIs the hashCode() method architecture/platform dependent?
It's up to the implementation, basically. From the docs:
As much as is reasonably practical, the
hashCode
method defined by classObject
does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the Java™ programming language.)
It would be valid for the Object.hashCode()
method to always return 0... it just wouldn't be very useful.
See more on this question at Stackoverflow