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?
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