I encountered this question during OCPJP.
Given the code:
public class Person {
private String name;
public Person(String name) {
this.name = name;
}
public boolean equals(Object o) {
if (!(o instanceof Person)) return false;
Person p = (Person)o;
return p.name.equals(this.name);
}
}
And the following statements (only one of which is true):
- A. Compilation fails because the hashCode method is not overridden
- B. A HashSet could contain multiple Person objects with the same name.
- C. All Person objects will have the same hash code because the hashCode method is not overridden
- D. If a HashSet contains more than one Person object with name="Fred" then removing another Person, also with name="Fred", will remove them all.
The answer is (B), but I don't understand why. Can somebody please explain this?