Sobes.tech
Junior — Middle

Is it possible to have multiple elements with identical keys in a HashMap?

sobes.tech AI

Answer from AI

In a HashMap in Java, keys must be unique in terms of meaning: if you add an element with a key that already exists in the map (according to the equals() method), the old value will be overwritten by the new one.

That is, you cannot have multiple elements with keys that are considered equal in content (equals). If you try to add such a key, the value will simply be updated.

Example:

Map<String, Integer> map = new HashMap<>();
map.put("key", 1);
map.put("key", 2); // overwrites the value for "key"
System.out.println(map.get("key")); // will output 2

If you need multiple values for a single key, usually Map<Key, List<Value>> or another data structure is used.