Junior — Middle
Is each key in a HashMap truly unique and non-repeating?
sobes.tech AI
Answer from AI
In HashMap, each key is indeed unique. If a key-value pair is added with a key that already exists, the old value for that key is overwritten with the new one. Thus, HashMap cannot have two elements with the same key, but values can be duplicated.
Example:
Map<String, Integer> map = new HashMap<>();
map.put("key1", 1);
map.put("key1", 2); // the value for "key1" will be updated to 2
System.out.println(map.get("key1")); // will print 2