问题
您的方法不起作用的原因是List#contains (documentation) 方法使用Person#equals 的结果来确定列表中的元素是否与参数相同。如果您尚未实现此方法,则会在Person 的继承树中搜索该方法。由于每个对象都继承自类Object,如果在通往Object 的路上没有类实现equals,您将退回到Object#equals (documentation)。然而,这个Object#equals 方法通过对象的身份(在内存中的位置)来比较对象。这意味着如果您创建一个具有相同属性(如 name 等)的对象,它只是一个副本,但与列表中的对象不同,每个身份。
请注意,StackOverflow 上有很多关于这个主题的问题。如果你不熟悉它,你应该检查一下。这是一个更详细解释它的示例:What issues should be considered when overriding equals and hashCode in Java?
有多种方法可以解决这个问题。
让我们首先考虑一个非常简单明了的方法。
手动迭代
我们手动迭代列表并检查有关相关参数的每个条目。
public Person lookupPerson(String personName) {
for (final Person person : persons) {
// Access properties of person, usage of getter methods would be good
if (person.name.equals(personName)) {
// Found matching person
return person;
}
}
// Traversed whole list but did not find a matching person
return null;
}
(就像在@DeepakS 的回答中看到的那样)
实现equals和hashCode,使用indexOf
现在我们让列表使用List#indexOf (documentation) 进行迭代和匹配部分。这种方法与您使用 contains (documentation) 的方法类似,但我们还希望获取元素,而不仅仅是检查它是否存在。
public class Person {
...
@Override
public boolean equals(final Object o) {
if (o == null) {
return false;
}
if (!(o instanceof Person)) {
return false;
}
if (o == this) {
return true;
}
final Person other = (Person) o;
return other.name.equals(this.name);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result;
if (this.name != null) {
result += this.name.hashCode();
}
return result;
}
}
以及查找方法:
public Person lookupPerson(String personName) {
// The needle to search for
final Person needle = new Person(personName);
// The needle will now be equals to list objects
// regarding its equals method which only checks
// for the name
final int index = persons.indexOf(needle);
if (index != -1) {
// Get the element at this position
return persons.get(index);
} else {
return null;
}
}
(就像在@AxelH 的回答中看到的那样)
紧凑型 Java 8 解决方案
如果您有 Java 8,您可能更喜欢非常紧凑的变体。因此,我们使用Stream#filter (documentation),它根据方法返回true 或false(所谓的Predicate (documentation))过滤流的元素。所以我们只需要在那里检查 name 就完成了。
public Person lookupPerson(String personName) {
return list.stream()
.filter(p -> p.name.equals(personName))
.findAny();
}
(就像在@GaneshToni 的回答中看到的那样)