Overriding the java equals() method - not working?
If you use eclipse just go to the top menu
Source --> Generate equals() and hashCode()
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.
Slightly off-topic to your question, but it's probably worth mentioning anyway:
Commons Lang has got some excellent methods you can use in overriding equals and hashcode. Check out EqualsBuilder.reflectionEquals(...) and HashCodeBuilder.reflectionHashCode(...). Saved me plenty of headache in the past - although of course if you just want to do "equals" on ID it may not fit your circumstances.
I also agree that you should use the @Override
annotation whenever you're overriding equals (or any other method).