How can you handle a case in which you have two "Dave"? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

How can you handle a case in which you have two "Dave"?

I tried it myself, and came up with an interesting result. import java.util.HashMap; public class MyClass { public static void main(String[ ] args) { HashMap<String, Integer> points = new HashMap<String, Integer>(); points.put("Amy", 154); points.put("Dave", 42); points.put("Dave", 777); System.out.println(points.get("Dave")); } } OUTPUT 777 As I noticed, it will get the last "Dave", instead of both. Is there a way to get both "Dave" values at the same time? Thanks in advanced.

29th Dec 2016, 5:34 AM
Fernando Cobo
Fernando Cobo - avatar
3 Answers
+ 1
A HashMap cannot contain duplicate keys. Adding a new item with a key that already exists overwrites the old element. You have to use different key, for example "Dave_2" ?
29th Dec 2016, 5:45 AM
sofroma
sofroma - avatar
+ 1
no you have get the last dave ,777 because hashmap doesn't support duplication of keys,even if you try it will overwrite the old key.so you can never get two of them as output.
29th Dec 2016, 7:35 AM
Rajveer
0
Thanks!
29th Dec 2016, 5:49 AM
Fernando Cobo
Fernando Cobo - avatar