When overriding the Object.equals()
method, there
are a number of conditions that must be met. Some of these conditions can be enforced
programmatically, such as:
Object
. Using
a specific type will result in unintuitive behaviour at least, because two
.equals()
methods will exist, and it might not be clear
in all cases which method will be calledObject.equals()
is overridden,
Object.hashCode()
should be overridden too. This
follows from the requirement that equal objects must have equal hash codes.
If no suitable hashCode() can be constructed, the method should throw an
UnsupportedOperationException
Since 0.6
Bad code: |
Good code: |
|
public boolean equals(MyClass s) { return this.name.equals(s.name); } |
@Override public boolean equals(Object o) { if (!(o instanceof MyClass)) { return false; } else { return this.name.equals(((MyClass)o).name); } } @Override public int hashCode() { return this.name.hashCode(); } |
|
The quick fix for this code check adds a hashCode()
method
if it does not yet exist.