LearnFrenzy
Sign in Take a free test

HashMap and TreeMap · Predict the Output · Question 8

LinkedHashMap in access order Answer, explanation & discussion

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

What is the output of the following Java program?

Main.java
import java.util.LinkedHashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        Map<String, Integer> m = new LinkedHashMap<>(16, 0.75f, true);
        m.put("a", 1); m.put("b", 2); m.put("c", 3);
        m.get("a");
        m.put("b", 20);
        m.getOrDefault("zz", 0);
        System.out.println(m.keySet());
    }
}
  • A [c, a, b] Correct
  • B [a, b, c]
  • C [b, a, c]
  • D [c, b, a]
Correct Answer: Option A

Accessing a and then updating b moves each to the end. Looking up a missing key changes nothing.

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