首页 > 解决方案 > 覆盖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 。

有人可以解释一下这种行为。

标签: javacollections

解决方案


当您首先在地图中添加新人时personsMap.put(person,"MyCar");,如果键不为空,则确定放置元素的位置。由hashcodekey的调用方法决定。之后有几个步骤,但对于此示例无关紧要。

由于您不覆盖hashcode()您的person并且otherPerson会有不同的hashcode.

当您尝试通过某个键获得价值时,也会发生同样的情况。为了找到元素所在的位置,hashcode()将被调用。但是otherPerson有不同hashcode,它会导致没有项目的位置 ( null)

equals()当在同一位置有许多元素(在列表或树结构中)时使用。然后找到正确的项目,他们将通过equals()方法进行比较


推荐阅读