Java Object.equals
equals, java, object
Solution
Methods in Java are virtual by default. In particular, `Object.equals` is virtual (since it's not declared `final`). Since `HashSet` overrides `Object.equals`1, you'll see the `HashSet` implementation of `equals` used when you invoke the virtual method on an object that has a runtime type of `HashSet` (remember dynamic dispatch depends on the runtime type of the receiving object, not the compile-time type).
1: We know that `HashSet` overrides `Object.equals` because the documentation says that `HashSet` derives from `AbstractSet` and the documentation for `AbstractSet.equals` says:
Compares the specified object with this set for equality. Returns `true` if the specified object is also a set, the two sets have the same size, and every member of the specified set is contained in this set (or equivalently, every member of this set is contained in the specified set). This definition ensures that the equals method works properly across different implementations of the set interface.
which clearly defines value equality whereas the default `Object.equals` is identity equality.
Problem
Can someone tell me why this returns true ? I thought if I cast something to e.g. `Object` and then call `.equals`, the default implementation from `Object` will be used. And s1 == s2 should return false. Please tell me under which topic I can find more about this behavior. ``` Set<String> s1 = new HashSet<String>(as("a")); Set<String> s2 = new HashSet<String>(as("a")); Object o1 = (Object)s1; Object o2 = (Object)s2; System.out.println(o1.equals(o2)); ```