When to use getClass() and instanceOf in Java
getClass() only gives equality if two objects belong to same class whereas instanceOf works for subtype also.
If two objects of different classes are checked for equal, then we use instanceOf . But once you use instanceOf at some level in the class hierarchy everything below it must use instanceOf or you will violatate the symmetry clause of equals contract.
e.g. any list can be equal to any list as long they have same elements iun the same order. So any List implementation equals() method must do instanceOf and not getclass() and then compare.
On the other hand, it only make sense for na instance of class X to be equal to another instance of class X ( and not any subclass ) , then use getClass().
Nice Explanation
ReplyDelete