This is probably a very basic question, but please help me understand where I'm going wrong. Please see below code -
I thought that if I override equals() method to compare if two objects of my User class are meaningfully equivalent, it'll give the same effect like Strings, when adding a similar object in a Set, but it's not. I tried a couple of things and in the end, simply returned "true" from the equals() method, but still the same result. What am I understanding/doing wrong here?
Thanks in advance!
ETA: Forgot to give the output - In the output, first set shows 2 elements "ABC" and "LMN", second set shows 2 elements 1 and 2, but third one shows 3 elements 2, 1, 1.
The problem is that you didn't override the hash code as you expected because you spelt the method name wrong (you used a lower case "c"). Since the default hashcode implementation was used, the hashcode was unique for each object so there was no need to invoke the equals method. You should always use the @Override statement when overriding methods to avoid this problem in the future:
Joined: Mar 11, 2007
Thanks a lot for pointing that out! I checked equals() method signature 2-3 times before posting the question.. should've done that for hashCode() method too.. Quite a silly mistake! Dunno where to hide
I would suggest always override hashcode() if you are overriding equals() and follow the contract which says if two objects are equal then there hashcode must be same. though its not required that if two objects are not equal then there hashcode must be different but its good to have to make it consistent.
Also think of compareTo() and compare() if you have data class like User in above case because you might need to provide sorting for your user either on natural order or in custom order.