jQuery in Action, 3rd edition
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Duplicate Elements 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 "Duplicate Elements" Watch "Duplicate Elements" New topic

Duplicate Elements

Ragu Sivaraman
Ranch Hand

Joined: Jul 20, 2001
Posts: 464
From: jaworski.com Mock Test
Which of the following may have duplicate elements?
1. Collection
2. List
3. Map
4. Set
Ans: 1, 2,
What about 3?
I know Map cant have duplicate Keys
But it can have duplicate elements
When we add 2 similar strings to a HashMap even though their
hashcode remains the same... the size is 2
Valentin Crettaz
Gold Digger

Joined: Aug 26, 2001
Posts: 7610
Maps may not have two keys being equal but it may have several values being equal. Those value must be mapped by different keys.
The following map is valid
"1" -> "String 1"
"2" -> "String 1"
"3" -> "String 2"
The following Map is not valid
"1" -> "String 1"
"1" -> "String 1"
"3" -> "String 2"
To sum up, the keys must be unique (as in a Set) but some values may be the same. That's why when you retrieve all keys from a HashMap they are returned as a Set (which does not allow duplicates), whereas when you retrieve all values they are returned as a Collection (which allows duplicates)

[Blog] [Blogroll] [My Reviews] My Linked In
I agree. Here's the link: http://aspose.com/file-tools
subject: Duplicate Elements
jQuery in Action, 3rd edition