Two meta points:
First, get used to using @Override every time you think you are overriding a method. This would result in your sample code not compiling, leading you to detect a problem.
Secondly, if you use the IDE, and it does not give you a nice bold warning, this is incorrectly configured! You have to fix it!
And if you are not using an IDE, you really should be. Once you have typed public boolean equals(Subclass other) , the text will change color and a warning message will appear telling you what your probable problem is.
By the way, the standard idiom for equals() that I converged with is this:
@Override public boolean equals(Object object) { if (object instanceof Subclass) { Subclass that = (Subclass) object; return this.anInt == that.anInt && this.aString.equals(that.aString); // for example } return false; }
In some cases, it is worth adding if (object == this) { return true; } if (object == this) { return true; } , but you really should not get used to it.
Kevin bourrillion
source share