Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Java by (10.2k points)

I'm using Eclipse to generate .equals() and .hashCode(), and there is an option labeled "Use 'instanceof' to compare types". The default is for this option to be unchecked and use .getClass() to compare types. Is there any reason I should prefer .getClass() over instanceof?

Without using instanceof:

if (obj == null)

  return false;

if (getClass() != obj.getClass())

  return false;

Using instanceof:

if (obj == null)

  return false;

if (!(obj instanceof MyClass))

  return false;

I usually check the instanceof option, and then go in and remove the "if (obj == null)" check. (It is redundant since null objects will always fail instanceof.) Is there any reason that's a bad idea?

1 Answer

0 votes
by (46k points)
If you use instanceof, making your equals implementation final will preserve the symmetry contract of the method: x.equals(y) == y.equals(x). If final seems restrictive, carefully examine your notion of object equivalence to make sure that your overriding implementations fully maintain the contract established by the Object class.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Aug 15, 2019 in Java by Krishna (2.6k points)

Browse Categories

...