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.