Preferred Usage of getClass() vs. instanceof in Generating .equals()
When utilizing Eclipse's code generator for .equals() and .hashCode(), you may encounter the option to use 'instanceof' for type comparison or .getClass(). The default selection is .getClass(), but this article examines whether there are any advantages to using .getClass() over instanceof.
Comparison Without instanceof:
if (obj == null) return false; if (getClass() != obj.getClass()) return false;
Comparison Using instanceof:
if (obj == null) return false; if (!(obj instanceof MyClass)) return false;
Typically, it is advisable to use the instanceof option and remove the "if (obj == null)" check, as null objects will inevitably fail instanceof. However, is this practice inherently erroneous?
Arguments for instanceof
Renowned Java expert Josh Bloch endorses this approach, citing the following reasoning:
Additional Resources
The above is the detailed content of `getClass()` vs. `instanceof` in Java\'s `.equals()` Method: Which is Better?. For more information, please follow other related articles on the PHP Chinese website!