LearnFrenzy
Sign in Take a free test

HashMap and TreeMap · Predict the Output · Question 18

Map.of with a duplicate key Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 18 Back to Exercise

What is the output of the following Java program?

Main.java
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        try {
            Map<String, Integer> m = Map.of("a", 1, "b", 2, "a", 3);
            System.out.println(m.size());
        } catch (IllegalArgumentException e) {
            System.out.print("IAE ");
        }
        try {
            Map.of("a", null);
        } catch (NullPointerException e) {
            System.out.println("NPE");
        }
    }
}
  • A IAE NPE Correct
  • B 2 NPE
  • C 3 NPE
  • D IAE null
Correct Answer: Option A

Map.of rejects duplicate keys (IllegalArgumentException) and nulls (NullPointerException).

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links