Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Object.equals

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));
like image 426
AlphaBeta Avatar asked Jun 16 '26 09:06

AlphaBeta


1 Answers

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.

like image 82
Brian Roach Avatar answered Jun 17 '26 23:06

Brian Roach