【发布时间】:2019-02-24 16:35:28
【问题描述】:
我重写了 Person 类的 equals 方法,比较类的 name 属性,如果它们相等,则从 equals 方法返回 true。
当我创建 Person 对象的实例并将其用作 hashmap 中的键时,在使用同名的新对象检索时,我无法从 hashMap 中检索回关联的值。
下面是我的
import java.util.HashMap;
导入 java.util.Map;
公共类 ToStringTest {
public static void main(String[] args) {
Person person = new Person("Jack", "California");
Map<Person,String> personsMap = new HashMap<>();
personsMap.put(person,"MyCar");
Person otherPerson = new Person("Jack", "California");
System.out.println(personsMap.get(otherPerson));
}
}
类人{
String name;
String city;
public Person(String name, String city) {
this.name = name;
this.city = city;
}
@Override
public String toString() {
return "Name : " + this.name + ", City : " + this.city;
}
@Override
public boolean equals(Object o) {
Person person = (Person) o;
if(person.name.equals(this.name)){
return true;
}
return false;
}
}
这是在使用 otherPerson 对象检索时打印 null。
谁能解释一下这种行为。
【问题讨论】:
-
别忘了
hashcode的实现
标签: java collections