LearnFrenzy
Sign in Take a free test

HashMap and TreeMap · Predict the Output · Question 10

A key that is changed after insertion Answer, explanation & discussion

  • Output
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 10 Back to Exercise

What is the output of the following Java program?

Main.java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        List<String> key = new ArrayList<>(List.of("a"));
        Map<List<String>, String> m = new HashMap<>();
        m.put(key, "first");
        key.add("b");
        System.out.println(m.get(key) + " " + m.get(List.of("a")) + " " + m.size() + " " + m.containsValue("first"));
    }
}
  • A null null 1 true Correct
  • B first null 1 true
  • C first first 1 true
  • D null first 1 true
Correct Answer: Option A

After the change, the key's hash points at a different bucket; a fresh ["a"] has the old hash but is no longer equal. The entry is stranded.

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