This week's giveaway is in the Spring forum.
We're giving away four copies of REST with Spring (video course) and have Eugen Paraschiv on-line!
See this thread for details.
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

Win a copy of REST with Spring (video course) this week in the Spring forum!
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: 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
subject: Duplicate Elements
It's not a secret anymore!