java - 覆盖equals方法不能在hashmap中使用对象作为键?
问题描述
我有 Person 类的 Overridden 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 。
有人可以解释一下这种行为。
解决方案
当您首先在地图中添加新人时personsMap.put(person,"MyCar");
,如果键不为空,则确定放置元素的位置。由hashcode
key的调用方法决定。之后有几个步骤,但对于此示例无关紧要。
由于您不覆盖hashcode()
您的person
并且otherPerson
会有不同的hashcode
.
当您尝试通过某个键获得价值时,也会发生同样的情况。为了找到元素所在的位置,hashcode()
将被调用。但是otherPerson
有不同hashcode
,它会导致没有项目的位置 ( null
)
equals()
当在同一位置有许多元素(在列表或树结构中)时使用。然后找到正确的项目,他们将通过equals()
方法进行比较
推荐阅读
- node.js - 如何使用多个 Express 应用程序 + NGINX 作为反向代理服务器来提供静态文件(CSS,...)
- javascript - 垂直对齐material-ui框
- flutter - 将其初始化为 dart 中的最终变量
- python - 如何更新和删除烧瓶网站中的 csv 数据
- c++ - 程序工作一次后每次都报错
- go - 字符串数据在内存中的位置
- php - 从逗号分隔值中选择列包含值的所有行
- r - 即使在将我的变量转换为 factor 之后,在运行 contrasts 函数时,它也会显示“对比仅适用于因子”
- sparql - 在 sparql 查询中查找大多数作者
- c# - 如何从 EF Core 构建的一对一关系中获取相关数据?