LearnFrenzy
Sign in Take a free test

Records, Enums and Sealed Classes · Predict the Output · Question 11

Records as HashMap keys Answer, explanation & discussion

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

What is the output of the following Java program?

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

record Seat(char row, int no) { }

public class Main {
    public static void main(String[] args) {
        Map<Seat, String> booked = new HashMap<>();
        booked.put(new Seat('B', 4), "Asha");
        booked.put(new Seat('C', 1), "Ravi");
        booked.put(new Seat('B', 4), "Meena");
        System.out.println(booked.size() + " " + booked.get(new Seat('B', 4)) + " " + booked.containsKey(new Seat('A', 1)));
    }
}
  • A 2 Meena false Correct
  • B 3 Asha false
  • C 2 Asha false
  • D 3 Meena true
Correct Answer: Option A

Equal records have equal hash codes, so the second B4 replaces the first.

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