Practice mode Java

What is the output of the Java code Map<String, Integer> m = new HashMap<>(); m.put(“a”, 1); m.put(“a”, 2); System.out.println(m.size() + ” ” + m.get(“a”));?

Correct answer B. 1 2

Explanation

A map holds at most one value per key, so the second put with an equal key replaces the earlier value instead of adding an entry. The size stays 1 and get returns the latest value, 2. The put method also returns the previous value, here 1, which allows callers to detect a replacement.

Report a problem

Answer checked How we write and check questions

Tip: press A, B, C or D to answer, and N for the next question.

Advertisement

Have a question about this answer?

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

Links and website addresses are not allowed in comments.