posted 13 years ago
Hello everybody,
if you have a look at the question 57 in the first practice exam you'll find that the correct answer is C. However the explanation says "Because Stuff doesn't override equals()". This is actually true but it should say "Because Stuff doesn't override equals() and hashcode()". Because if the class Stuff doesn't override hashcode() as well, the objects are all different.
So let's imagine we override equals like this:
public boolean equals(Object obj) {
return this.value == ((Stuff) obj).value;
}
Even in this case, if we don't override the hashcode method, the set will add every new object in a different hashcode bucket and won't execute equals() against any other object. If we override the hashcode like this:
public int hashCode() {
return 4;
}
Even though this is a very inefficient override of the hashcode method (every object will be in the same bucket) the set will be able to compare the objects.
Regards!