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));
Because that's exactly what the Javadocs say it will do:
public boolean equals(Object o)
Compares the specified object with this set for equality. Returns true if the given object is also a set, the two sets have the same size, and every member of the given set is contained in this set. This ensures that the equals method works properly across different implementations of the Set interface.
Just because you cast it to Object doesn't change what it actually is. The over-ridden equals() method in HashSet is used.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With