Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Duplicate Elements

 
Ragu Sivaraman
Ranch Hand
Posts: 464
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Anythoughts?
 
Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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)
Val
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic