Java Collection Map : 如何使用 containsValue 函数检索映射的对象



我是Java集合的新手,所以我尝试使用Map进行编码。我这样设置我的收藏

    Map<Integer, Person> people = new HashMap<>();                                     
    people.put(1, new Person("Arnold", "Maluya", 25));
    people.put(2, new Person("Mison", "Drey", 3));
    people.put(3, new Person("James", "Valura", 54));
    people.put(4, new Person("Mikee", "Sandre", 24));

所以我的目标是我想检查人们是否包含像"new Person("Arnold","Maluya",25)这样的对象,所以我所做的是这个

 boolean test = people.containsValue(new Person("Arnold", "Maluya", 25));
 System.out.println(test);

我得到的是"错误"的结果。 那么我做对了吗,所以如果总和是错误的,我错过了什么?

实现一个 equals,示例:

public class Person {
private String name;
private String lastName;
private String age;
@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;
    Person person = (Person) o;
    if (name != null ? !name.equals(person.name) : person.name != null) return false;
    if (lastName != null ? !lastName.equals(person.lastName) : person.lastName != null) return false;
    return age != null ? age.equals(person.age) : person.age == null;
}
@Override
public int hashCode() {
    int result = name != null ? name.hashCode() : 0;
    result = 31 * result + (lastName != null ? lastName.hashCode() : 0);
    result = 31 * result + (age != null ? age.hashCode() : 0);
    return result;
}
}

hashCode() 和 equals() 方法在插入到 Java 集合中的对象中扮演着不同的角色。

equals() 在大多数集合中用于确定集合是否包含给定元素。

将对象插入 hastable 时,使用键。计算此键的哈希代码,并用于确定在内部存储对象的位置。当您需要在哈希表中查找对象时,您还需要使用键。计算此键的哈希代码,并用于确定在何处搜索对象。

当你在集合中使用自定义Java对象时,总是建议覆盖hashCode()和equals()方法,以避免奇怪的行为。

该行为是正确的,因为您没有覆盖类Person equals 方法。 Map将咨询存储在其中equals对象的方法,以确定查询是否与存储的值匹配。必须重写对象中的 equals 方法并相应地实现逻辑,以确定作为参数传递的对象是否匹配。

注意:下面的代码不检查空值,因此可能会引发异常。您需要放置其他条件以避免空指针异常。

@Override
public boolean equals(Object obj) {
    if (!(obj instanceof Person)) {
        return false;
    }
    Person other = (Person) obj;
    if ((other.firstName.equals(this.firstName)) && (other.lastName.equals(this.lastName))
            && (other.age == this.age)) {
        return true;
    }
    return false;
}

最新更新