【问题标题】:Overriding equals method not working on using object as key in hashmap?覆盖equals方法不能在hashmap中使用对象作为键?
【发布时间】: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


【解决方案1】:

当您在地图personsMap.put(person,"MyCar"); 中添加新人时,首先如果key 不为空,则确定该元素的放置位置。它是通过调用hashcode 方法确定的。之后有几个步骤,但对于本例来说无关紧要。

由于您不覆盖hashcode(),因此您的personotherPerson 将具有不同的hashcode

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

equals() 在同一位置有很多元素(在列表或树结构中)时使用。然后通过equals()方法比较找到合适的项目

【讨论】:

  • 我尝试覆盖 Person 类的 hasCode 方法,它成功了。能够使用 otherPerson 对象从地图中检索对象。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-09
  • 1970-01-01
  • 2010-09-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多