Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

how does Set understands duplicate elements?

 
amit daundkar
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How does Set understand if duplicate element is inserted? I mean does it perform "equals" test everytime an object is inserted?

Please reply.
Thanks.
 
Viktor Kubinec
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In order to understand this, you should first understand hashCode and equals contract.

Find HashSet on this site :
Set interface

If hashCodes equal and objects equal, then the insertion is resolved as duplicated element and the add method returns false.
 
Henry Wong
author
Marshal
Pie
Posts: 21127
78
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

It''s also implementation specific. For example, the TreeSet uses either the Comparable or Comparator interfaces.

Henry
 
amit daundkar
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Viktor, Henry.
 
Hemant B. Kumar
Greenhorn
Posts: 11
Java Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Henry Wong wrote:
It''s also implementation specific. For example, the TreeSet uses either the Comparable or Comparator interfaces.

Yeah that's right but I think in that case also it would be using equals and hashcode method, isn't it?
 
Henry Wong
author
Marshal
Pie
Posts: 21127
78
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hemant B. Kumar wrote:
Henry Wong wrote:
It''s also implementation specific. For example, the TreeSet uses either the Comparable or Comparator interfaces.

Yeah that's right but I think in that case also it would be using equals and hashcode method, isn't it?



Interestingly, the answer is no. The reason it is interesting is because if you look at the JavaDoc for java.util.Set, it is actually defined as using the equals() method to determine duplicates. However, the java.util.TreeSet class does not use the method -- and the JavaDoc explicitly mentions that it is the programmers responsibility to guarantee that it is consistent -- meaning that if Comparable or Comparator says that two objects are equal, the equal() method should return equal.

Henry
 
Rob Spoor
Sheriff
Pie
Posts: 20533
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If it isn't you can get odd behaviour. For instance:
What you now get is that set3.equals(set1) but !set1.equals(set3).
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic