File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Marcus Green Q=21 Collection Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Marcus Green Q=21 Collection" Watch "Marcus Green Q=21 Collection" New topic
Author

Marcus Green Q=21 Collection

Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944


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: 12761
    
    5
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

Joined: Nov 22, 2008
Posts: 18944
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: 18671
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
Plus, this is why the Double equals() method returns true if two
NaN values are compared!

Khalid
------------------
\\ //
~\// irucidal~


\\ //<BR>~\// irucidal~
 
 
subject: Marcus Green Q=21 Collection
 
Similar Threads
TreeSet uses compareTo
new SCJP in town :)
Overall performance of ArrayList vs. HashSet
Collections
java