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
Joined: Mar 22, 2000
Posts: 12268
1
posted
0
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
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
Joined: Jan 30, 2000
Posts: 18670
posted
0
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>
"I'm not back." - Bill Harding, Twister
Khalid Bou-Rabee
Ranch Hand
Joined: Jul 12, 2000
Posts: 54
posted
0
Plus, this is why the Double equals() method returns true if two NaN values are compared! Khalid ------------------ \\ // ~\// irucidal~
\\ //<BR>~\// irucidal~
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to
run our stuff on 16 servers instead of 3.