Some objects are considered the same if they have the same contents. For those, use .equals(Object)
to compare object contents.
Some objects are considered the same if they are the same instance. For those, use ==
to compare object instances.
You can alter an Object's content comparison by overriding public boolean equals(Object)
, but if you do so, remember that you must abide by three rules for the rest of the Java framework to work properly.
- Reflexive: a.equals(a) must be true.
- Symmetric: if a.equals(b), hen b.equals(a) must be true.
- Transitive: if a.equals(b) and b.equals(c) then a.equals(c) must be true.
In addition, the equality operation should be consistent, such that if a.equals(b) and no updates are made to a or b, then a.equals(b) should remain true.
Once you override equals, you can gain performance improvements in the hash related collections by overriding public int hashcode()
to return identical values whenever equals(...)
would return true. Also, it should have a very low chance of returning identical values if equals(...)
returns false. There is not need to make a "perfect" hash, which is one where hashcode(...)
is guaranteed to return different values if equals(...)
returns false, because all of the Java Collections routines check equals(...)
after checking for possible equality with hashcode(...)
.