Java Object. equals
Can someone tell me why this returns true?
Please tell me under which topic I can find more information 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));
Solution
Methods in Java are virtual by default In particular, object Equals is virtual (because it is not declared final) From HashSet overrides object Starting with equals1, you'll see a HashSet implementation of equal when calling a virtual method on an object of runtime type HashSet (remember that dynamic dispatch depends on the runtime type of the receiving object, not the compile time type)
1: We know that HashSet will overwrite object Equals, because Documentation means that HashSet is derived from abstractset, while abstractset The equals document says:
It explicitly defines equal values, and the default object Equals is identity equality