有人知道这个问题的答案吗?为了考试而学习,看起来就好了。
b) Amend the Person class so the code snippet below will work properly
ArrayList<Person> people = new ArrayList<Person>();
//Assume Person objects have been added to the list
if (people.contains(new Person("Adam Ant", 48)))
{
//Do something
}
else
{
//Do something else
}
答案 0 :(得分:1)
修改Person类,以便下面的代码片段正常工作
覆盖Object.equals(Object)
中的Person
。像,
@Override
public boolean equals(Object obj) {
if (obj instanceof Person) {
Person p = (Person) obj;
return this.name.equals(p.name) && this.age == p.age;
}
return false;
}
覆盖hashCode
(或您的Person
无法正常使用某些Collection
s)也是一种很好的做法。像,
@Override
public int hashCode() {
return name.hashCode() + age;
}