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

时间:2017-10-16 08:05:13

标签: java dictionary

我是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));

所以我的目标是我想检查人们是否包含像#34; new Person(&#34; Arnold&#34;,&#34; Maluya&#34;,25)&#34;所以我所做的就是这个

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

 System.out.println(test);

我得到&#34;假&#34;结果。所以我说得对,所以如果一切都错了我错过了什么?

3 个答案:

答案 0 :(得分:3)

实现等于,例如:

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;
}
}

答案 1 :(得分:1)

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

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

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

在集合中使用自定义java对象时,始终建议覆盖hashCode()&amp; equals()方法,以避免奇怪的行为。

答案 2 :(得分:0)

行为是正确的,因为您没有覆盖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;
}