LearnFrenzy
Sign in Take a free test

HashMap and TreeMap · Predict the Output · Question 14

Keys that are equal but different objects Answer, explanation & discussion

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

What is the output of the following Java program?

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

record Emp(int id) { }

public class Main {
    public static void main(String[] args) {
        Map<Emp, String> m = new HashMap<>();
        m.put(new Emp(1), "Asha");
        m.put(new Emp(1), "Asha K");
        m.put(new Emp(2), "Ravi");
        Map<String, Integer> s = new HashMap<>();
        s.put(new String("pin"), 1);
        s.put("pin", 2);
        System.out.println(m.size() + " " + m.get(new Emp(1)) + " " + s.size() + " " + s.get("pin"));
    }
}
  • A 2 Asha K 1 2 Correct
  • B 3 Asha 2 1
  • C 2 Asha 1 1
  • D 3 Asha K 2 2
Correct Answer: Option A

Maps compare keys with equals and hashCode, not ==. Records and Strings implement both.

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