I ran into an interesting (and very frustrating) issue with the equals()
method today which caused what I thought to be a well tested class to crash and cause a
In Java, the equals()
method that is inherited from Object
is:
public boolean equals(Object other);
In other words, the parameter must be of type Object
. This is called overriding; your method public boolean equals(Book other)
does what is called overloading to the equals()
method.
The ArrayList
uses overridden equals()
methods to compare contents (e.g. for its contains()
and equals()
methods), not overloaded ones. In most of your code, calling the one that didn't properly override Object
's equals was fine, but not compatible with ArrayList
.
So, not overriding the method correctly can cause problems.
I override equals the following everytime:
@Override
public boolean equals(Object other){
if (other == null) return false;
if (other == this) return true;
if (!(other instanceof MyClass)) return false;
MyClass otherMyClass = (MyClass)other;
...test other properties here...
}
The use of the @Override
annotation can help a ton with silly mistakes.
Use it whenever you think you are overriding a super class' or interface's method. That way, if you do it the wrong way, you will get a compile error.