The Ideal .equals()
Method in Java
This is straight up copied from my Effective Java notes, you should go read that book if you haven’t.
To implement the ideal equals
method:
* Use the ==
operator to check for the same reference. (performance optimization, but potentially worth it)
* Use the instanceof
operator to catch nulls and ensure the argument can be cast.
* Cast the argument
* For each significant field in the class, check for matches.
* For float
or double
use the boxed class compare()
methods
* For primitives, use ==
* For objects, call equals
recursively.
Ensure your equals
is symmetric, transitive, and reflexive.
Make sure you override hashCode
as well.