Junior — Middle
How is the addition of elements to a HashMap in Java performed?
sobes.tech AI
Answer from AI
In Java, the method put(key, value) is used to add elements to a HashMap. It adds a key-value pair to the map. If the key already exists, the old value will be replaced with the new one.
Example:
import java.util.HashMap;
public class Example {
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>();
map.put("apple", 3); // add element
map.put("banana", 5); // add another element
map.put("apple", 10); // replace value for key "apple"
System.out.println(map); // Output: {banana=5, apple=10}
}
}