Junior — Middle
Can you explain how elements are added to a Map data structure?
sobes.tech AI
Answer from AI
In Java, to add elements to a Map, the put(key, value) method is used. It takes a key and a value, and adds them to the collection. If the key already exists, the value for that key is overwritten with the new one.
Example:
Map<String, Integer> map = new HashMap<>();
map.put("apple", 3); // adding a key-value pair
map.put("banana", 5); // adding another pair
map.put("apple", 10); // overwriting the value for the key "apple"
As a result, the map will contain two entries: "apple" -> 10 and "banana" -> 5.
Important:
- Keys in a
Mapmust be unique. - Values can be duplicated.
- The order and performance may vary depending on the implementation of
Map(e.g.,HashMap,TreeMap).