hashmap - unusual behaviour of HashCode in java -


i stuck around while studying hashcode() in java. wrote 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 returning x again     key.type="null";     system.out.println(key.hashcode());// it's returning x again. 

}

i confused how possible after changing value contained within key hashcode same. it's literally breaking immutable key concept.

is hashcode() method architecture/platform dependent?

i confused how possible after changing value contained within key hashcode same. it's literally breaking immutable key concept.

nope, it's fine. you're not overriding equals or hashcode, it's not using value of type field part of equality comparison... it's using reference identity, effectively. key still refers same object did, it's entirely sensible return same hash code. nothing affecting hash code or equality has changed.

if want shared type useful key in map, i'd suggest:

  • overriding hashcode() , equals(), making sure obey relevant contracts
  • preventing instances being mutated in equality-affecting ways
  • renaming clearer it's meant represent

is hashcode() method architecture/platform dependent?

it's implementation, basically. docs:

as reasonably practical, hashcode method defined class object return distinct integers distinct objects. (this typically implemented converting internal address of object integer, implementation technique not required java™ programming language.)

it valid object.hashcode() method return 0... wouldn't useful.


Comments