Java集合映射:如何使用containsValue函数检索映射的对象
我是java集合的新手,所以我尝试使用Map编写代码。 我把我的收藏设置成这样Java集合映射:如何使用containsValue函数检索映射的对象,java,dictionary,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));
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));
这就是我得到的“假”结果。那么,我做对了吗?如果sumthing错了,我错过了什么?方法hashCode()和equals()在插入Java集合的对象中扮演着不同的角色
equals()在大多数集合中用于确定集合是否包含给定元素
将对象插入hastable时,使用键。将计算该键的哈希代码,并用于确定对象在内部的存储位置。当需要在哈希表中查找对象时,还需要使用键。该键的哈希代码被计算并用于确定在何处搜索该对象
在集合中使用自定义java对象时,最好重写hashCode()&equals()方法,以避免出现奇怪的行为。实现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;
}
}
该行为是正确的,因为您没有重写
Person
类中的equals方法Map
将使用存储在其中的对象的equals
方法来确定查询是否与存储的值匹配。您必须重写对象中的equals
方法,并适当地实现逻辑,以确定作为参数传递的对象是否匹配
注意:下面的代码不检查空值,因此可能引发异常。您需要设置附加条件以避免空指针异常
您必须在类Person中实现方法“equals”。请看omg不知道,谢谢您提供的信息elysrivero99:)谢谢您jaydeep先生非常有用的信息非常感谢:)
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;
}
}
@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;
}