2004-07-28

Java - instaceof vs equals()

Java instaceof vs equals()

I've been doing some code reviews lately and found that programmers across the team have used different means of comparing object instance equality.

1. There are those who use "instanceof" of check if an object is an instance of a given concret type:
if (theObject instanceof TypeA) {
 // do something based on TypeA
} else if (theObject instanceof TypeB) {

 // do something based on TypeB
} else {
 // do something else
}

2. We also have constant class identifiers defined of type Long, that are guaranteed to be unique for all classes for the base object types in our data model. There are some programmers who make use of the equals() method for comparison :
if (theObject.getClassID().equals(InstanceTypeEnumeration.TYPEA)) {
 // do something based on TypeA
} else if (theObject.getClassID().equals(InstanceTypeEnumeration.TYPEB)) {
 // do something based on TypeB
} else {
 // do something else
}

I've no idea as yet, about which one's better...