public class Person {
private String name;
public Person(String name) { this.name = name; }
public boolean equals(Person p) {
return p.name.equals(this.name);
}
}
Which statement is true?
A. The equals method does NOT properly override the Object.equals method.
B. Compilation fails because the private attribute p.name cannot be accessed in line 5.
C. To work correctly with hash-based data structures, this class must also implement the
hashCode method.
D. When adding Person objects to a java.util.Set collection, the equals method in line 4 will
prevent duplicates.
Answer: A
这是一个模拟考试的问题,我正在准备 ocjp 6,我对选项 C 有疑问。它说“正常工作”,所以这是否意味着需要覆盖哈希码?虽然不覆盖hashcode()
会起作用,但我专注于“正确”这个词!