contains() uses equals(). If you don't override the equals() method, an instance of a class will only be equal to itself. If you add A into the set, and check if the set contains A, it will be true, because A.equals(A) is true.
checkEquals.equals(checkEquals1) returns false because checkEquals and checkEquals1 are different instances. testSet.contains returns true for the reason I have explained above.
then why its required to overide equals when using custom objects with hashset?
When you don't want two objects meaningfully equal to be in the same set. Let's say that you don't want two CheckEquals instance with the same name to be there. With your actual code, you can insert two different instances with the same name :
Both will print true, proving that both instances were inserted in the set.
If you want to avoid that, you'll have to override equals() and hashCode():
(not testing for null here)
Now, true and false will be output. The second instance will not be inserted because the equally same object was already in there.
Same. containsKey will use the equals() method, which explains why youre getting true. If you don't override hashCode, all your objects will end up in the same bucket, which is not very efficient if you have many objects in your map. That won't prevent you from fetching them though.