What is the behavior of the Map.of() method when invoked with duplicate keys?

Java MCQ: What is the behavior of the Map.of() method when invoked with duplicate keys?

a) It merges the values of the duplicate keys
b) It replaces the previous key with the new one
c) It throws an IllegalArgumentException
d) It removes the duplicate key

Answer:

c) It throws an IllegalArgumentException

Explanation:

The Map.of() method in Java 9 throws an IllegalArgumentException when invoked with duplicate keys. The method is designed to create an immutable map, and one of the constraints is that the map cannot contain duplicate keys. Attempting to create a map with duplicate keys using Map.of() will result in an exception being thrown.

Here’s an example that demonstrates this behavior:

import java.util.Map;

public class MapOfDuplicateKeysExample {
    public static void main(String[] args) {
        // This will throw IllegalArgumentException due to duplicate keys
        Map<String, Integer> ages = Map.of("John", 25, "Jane", 30, "John", 35);
    }
}

In this example, the Map.of("John", 25, "Jane", 30, "John", 35) statement will throw an IllegalArgumentException because the key “John” appears twice. This strict enforcement of unique keys by Map.of() ensures the immutability and consistency of the map.

Reference links:

https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top