The Artima Developer Community
Sponsored Link

Legacy Design Forum
Canonical Object Idiom



This page contains an archived post to the Design Forum (formerly called the Flexible Java Forum) made prior to February 25, 2002. If you wish to participate in discussions, please visit the new Artima Forums.


Re: Simpler code for equals(); please review

Posted by Michael on January 24, 2000 at 1:25 AM

> The code for equals() in the article ensures that the Object passed as an argument is of the same type
> as itself by trying a typecast; failure results in a ClassCastException which is caught
> I saw this simpler code elsewhere:
> if (obj != null && (obj instanceof this.getClass()))
> Is this OK? Or are there any hidden glitches in this that aren't apparent to me?

Yes, it's OK, but it could still be even shorter. It's OK to use a null reference with
the instanceof operator, it'll just return false. Also, there's little need for the
method call to get the current class's class, since you're in that file anyway.


public boolean equals(Object o) {
if( !( o instanceof Worker )) {
return false;
Worker w = (Worker) o;
return (name.equals( && doList.equals(w.doList));


In addition, I have no problem with the readability of the previously
posted version of equals(...),

class A {
public boolean equals(A a) {
/* make sure a!=null, otherwise just compare members */
public boolean equals(Object o) {
return (o instanceof A)? equals((A) o) : false;

(...I assume the "performance" advantage that was suggested is found in the
potential frequency of calling equals() with another object of the same reference
type (ie, A::equals(A)), thus preventing the polymorphic lookup and the unnecessary
"instanceof" call??)



Sponsored Links

Copyright © 1996-2009 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us