When implementing equals
, before checking if the objects are equal you should consider the next scenarios:
- The two are actually references to the same object
- The
other
object isnull
- The
other
object is an instance of a different type
and when checking equality between the two objects you should consider the nullness
of every field involved in the comparison too. In most IDEs equals
can be generated automatically, in eclipse:
Alt + Shift + s --> Generate hashCode() and equals()
the next is generated by eclipse:
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
A other = (A) obj;
if (denominator == null) {
if (other.denominator != null)
return false;
} else if (!denominator.equals(other.denominator))
return false;
if (numerator == null) {
if (other.numerator != null)
return false;
} else if (!numerator.equals(other.numerator))
return false;
return true;
}