Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why is this HashSet allowing duplicates?

 
Vidhya Ramaswamy
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Question taken from LearnKey MasterExam.
Why is the set allowing duplicates, and showing the size as 2?
I understand, it is because the equals() is not properly overridden, it doesn't take an Object. So, is the set allowing duplicate because of the equals() in Nearly class?
 
Ankit Garg
Sheriff
Posts: 9529
33
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes! the equals method must take an Object parameter to make it a successful override and then it will not allow duplicates...
 
Vidhya Ramaswamy
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Ankit for your quick response.
Is this what happens?
calls equals() in the Nearly class.
equals() and hashCode() are called before adding to HashSet. But here, the equals() called is of Object class(since Nearly class does not override equals() properly. So, n2 is added to the set.
Please correct me if I'm wrong.
 
Ankit Garg
Sheriff
Posts: 9529
33
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are right. But if you change your code to something like this, then see the output. Change this

if(n1.equals(n2))s+="1";

to this

Object obj = n2;
if(n1.equals(obj))s+="1";

Now you will see that the objects are now not equal as the equals method in Object class will be called now instead of equals in Nearly class...
 
Preethi Dev
Ranch Hand
Posts: 265
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Ankit,
i tried this program ,as you have mentioned(i.e replacing Object b=n2)

but it still shows set.size() as 2. if it overrides equals() in object, then how it allows to add the second one?
please clear this too....

Thanks
Preetha
 
Vidhya Ramaswamy
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Preetha,

Replacing the code with
Object obj = n2;
if(n1.equals(obj))s+="1";

calls the Object class equals(), which just does a direct compare(==).
So, 1 is not printed in this case.

The reason it shows set.size() as 2 is because both the references do not refer to the same object, as(n1!=n2).

Try this out(assigns n1 to obj, so both refer to the same object):

Object obj = n1;
if(n1.equals(obj))s+="1"; //calls Object class equals()
if(n1==n2)s+="2";
Set<Nearly> set = new HashSet<Nearly>();
set.add(n1);
set.add((Nearly)obj); //trying to add duplicate
System.out.println(s + " " + set.size());

Now, set.size() will print 1.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic