作者:鱼和鱼还有鱼3_Mh_qet | 来源:互联网 | 2022-10-22 14:28
Trying to check how hashmap works
public class hashmapcheck {
public static void main(String args[]) {
Person abhishek = new Person("abhishek");
Map mapCheck = new HashMap();
mapCheck.put(abhishek,"ancd");
abhishek.setName("defg");
System.out.println(mapCheck.get(abhishek)); //line which i try to undertand
}
}
public class Person {
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Person(String name) {
this.name = name;
}
String name;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
return name != null ? name.equals(person.name) : person.name == null;
}
@Override
public int hashCode() {
return name != null ? name.hashCode() : 0;
}
}
if equals and hashcode is not overriden for person class it print ancd, but when i override it it will print null.
what i thought when i store objectin hashmap it will store reference of that hashmap what is going wrong
1> Eran..:
abhishek.setName("defg")
is mutating a key of your HashMap
(a Person
instance) after you added it to the HashMap
.
This causes the hashCode()
of that key to change, so the get()
method fails to locate it according to the new hashCode()
(since it was placed in a bin that matches the original hashCode()
.
You are misusing the HashMap
class. Keys should not be mutated after being added to the HashMap
(at least properties that affect the outcome of hashCode
and equals
should not be mutated).
至于不覆盖equals
和时的行为hashCode
,在这种情况下,equals
asnd hashCode
不依赖于的值name
,因此更改make 不会name
造成任何影响。在这种情况下,HashMap
如果您要搜索与Person
放入的实例完全相同的实例,则默认实现可确保您可以在中找到密钥Map
。