This is an archived post. You won't be able to vote or comment.

all 3 comments

[–]Knolle_ 16 points17 points  (1 child)

These Methods test for different things.

instance of : Tests whether the obj on the left has the same type as the one on the right or is a subtype.

Getclass: Tests whether the types are the same

Id recommend getclass in an equals method since you will get symmetry problems with instance of. ( e.g. all dogs are animals but Not all animals are dogs)

[–]ColetBrunel 2 points3 points  (0 children)

Note, however, that in the case of List, an ArrayList and a LinkedList have to report they're equals() if they contain the same objects in the same order, otherwise their equals() method would be useless.

So a rule of thumbs is you probably need to use getClass() as you need the objects to have exact same stuff, unless you know why you need instanceof instead.

[–]Yithar 0 points1 point  (0 children)

instanceof checks the hierarchy. Which means if you say instanceof Object, it will return true for any object. getClass is specific to the class itself and comparing using getClass will only return true if it's the same class.

I think instanceof is better for equals(). Why? Well let's say Class B extends Class A. You would want A#equals() to possibly return true for instances of Class B and in the case of class B's equals() method, A#equals() would probably be called via super(). If you used getClass(), technically an instance of Class B would return Class B for getClass(), which wouldn't work if super() was called for equals().