Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Marcus Green Q=21 Collection

 
Anonymous
Ranch Hand
Posts: 18944
  • 0
  • send pies
  • Quote
  • Report post to moderator


How does the set collection deal with duplicate elements?
1) An exception is thrown if you attempt to add an element with a duplicate value
2) The add method returns false if you attempt to add an element with a duplicate value
3) A set may contain elements that return duplicate values from a call to the equals method
4) Duplicate values will cause an error at compile time

Hi all
The answer of the above question is 2 and I know it ..I am just confused about 3

A set may contain elements that return duplicate values from a call to the equals method

what does it mean..if some one can explain...
Wali

 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13045
6
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It simply means that a Set can contain two references to two objects that return true when compared with equals()
Long aL = new Long( 1024 );
Long bL = new Long( 1024 );
Two separate objects but aL.equals( bL ) returns true.
Bill
 
Anonymous
Ranch Hand
Posts: 18944
  • 0
  • send pies
  • Quote
  • Report post to moderator
then answer 3 should also be true, shouldn't it?
i m also confused with this question, please clarify it.
thanks,
DS
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, 3 is false. That's what makes a Set different from a List - no duplicates are allowed in a Set. And "duplicates" are defined as objects for which equals() returns true.
Using Bill's objects aL and bL, what happens if you try to add them both to the same Set?
<code><pre>
Set set = new HashSet();
System.out.println(set.add(aL)); // prints true
System.out.println(set.add(bL)); // prints false

// show whole Set
// (which turns out to include only one element)
Iterator it = set.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
</pre></code>
 
Khalid Bou-Rabee
Ranch Hand
Posts: 54
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Plus, this is why the Double equals() method returns true if two
NaN values are compared!

Khalid
------------------
\\ //
~\// irucidal~
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic