New course! Every coder should learn Generative AI!
Try a free lesson0
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.
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" ?
+ 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.
0
Thanks!