On the code:
person P1 = new Person ("Xiaoer", 1); person P2 = new Person ("San", 4); map<person,string> maps = new hashmap<person,string> (); Maps.put (P1, "1111"); Maps.put (P2, "2222"); SYSTEM.OUT.PRINTLN (maps); Maps.put (P2, "333"); SYSTEM.OUT.PRINTLN (maps); P1.setage (5); SYSTEM.OUT.PRINTLN (maps); Maps.put (P1, "333"); SYSTEM.OUT.PRINTLN (maps); System.out.println (Maps.get (p1));
Output Result:
{person [Name=san, age=4]=2222, person [Name=xiaoer, age=1]=1111}
{person [Name=san, age=4]=333, person [Name=xiaoer, age=1]=1111}
{person [Name=san, age=4]=333, person [Name=xiaoer, age=5]=1111}
{person [Name=san, age=4]=333, person [Name=xiaoer, age=5]=1111, person [Name=xiaoer, age=5]= 333}
333
Focus on the red callout.
Where the person class is as follows:
Class person{private String name; private int age; @Override public int hashcode () {final int prime = 31; int result = 1; result = Prime * result + age; result = Prime * result + ((name = = null)? 0:name.hashcode ()); return result; }/* (non-javadoc) * @see java.lang.object#equals (java.lang.Object) */@Override public boolean equals (Ob Ject obj) {if (this = = obj) return true; if (obj = = null) return false; if (getclass () = Obj.getclass ()) return false; person other = (person) obj; if (age! = Other.age) return false; if (name = = null) {if (other.name! = null) return false; } else if (!name.equals (Other.name)) return false; return true; }/* (non-javadoc) * @see java.lang.object#tostring () */@Override public String toString () {Retu RN "Person [name=" + NAme + ", age=" + Age + "]"; }}
Why? The output maps appear with the same key.
The preliminary judgment is related to the hashcode mechanism of HASHMAP, which detects the hash value of the element key only when the element add is added to the map for the first time. After I changed the value of the object by external means, and then added the object to the map, in fact, from the hashcode view is already a new object, so Map think their key is different. HashMap to improve the calibration speed, it does not compare the elements that are being added to all the elements that are already in the map, but just a quick comparison of hashcode table tables? Although they are actually the same object from physical memory.
What is the rationale behind this design in Java?
In fact, there is no security. For example, I passed a HashMap object to method A to deal with, and as result A is still being processed, I changed the value of an element in the HashMap object to the introduction, and a is not yet known.
What's the matter with hashmap thread insecurity?
Duplicate key appears in Java HashMap for explanation