The key points here are:
- Given the implementation of your equals() method, the objects pointed to p3 and p5 are equal because their name String instances point to exactly the same object in the heap (this is due to the fact that you use String literals for the arguments of the Person constructor.) Try to instantiate p5 using new String("jane") as the argument instead, and see what you get.
- Even though you get the output which indicates that p5 is in the set, that doesn't mean that the object pointed to by p5 was added to the set. Actually it wasn't. What it means is that a object equal to the one pointed to by p5 was added to the set (in this case p3.) You can
test this by augmenting the Person class with an additional instance variable which doesn't affect the hashCode() or equals() values, setting it differently for p3 and p5, and then testing the value after retrieval from the set.
-
You should change your equals() method to use the String.equals() method instead of the == operator. The equals() method is checking for logical equality, and to have the equals() result differ on whether you instantiate an object using a String literal or a newly instantiated String object is bound to create problems.