In the post What issues should be considered when overriding equals and hashCode in Java? one explains in great detail how to write proper equality method in Java using getClass to compare RUntime types of two objects we equate. I understand that the reason we do this is to make sure that if B extends A we want a.equals(b) = b.equals(a) (reflexivity).
It does provide a big limitation in my opinion. If you have a collection of objects A, inswert a few B objects as they are subclasses of A, then a.equals(b) is always false… Perhaps, at certain times, we should stick to the old instanceof operator to provide polymorphism and allow equality of subtypes? What are your thoughts?
You need only look as far as
java.utilto see examples of where.equals()gets redefined to care only about interface. For example,java.util.List, where the relevant characteristics equality is defined, and the formula for calculating the hash code is explicitly documented.So to answer your question, yes — ignoring subtypes makes sense under certain circumstances. But I like Josh Bloch’s approach to this by making an interface the aspect of equivalence.