LearnFrenzy
Sign in Take a free test

Object Class and Wrapper Classes · Predict the Output · Question 20

equals, hashCode and toString generated by a record Answer, explanation & discussion

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

What is the output of the following Java program?

Main.java
import java.util.HashSet;
import java.util.Set;

record Coin(String currency, int value) { }

public class Main {
    public static void main(String[] args) {
        Coin a = new Coin("INR", 5), b = new Coin("INR", 5);
        Set<Coin> set = new HashSet<>(Set.of(a));
        set.add(b);
        System.out.println(a + " " + (a == b) + " " + a.equals(b) + " " + (a.hashCode() == b.hashCode()) + " " + set.size());
    }
}
  • A Coin[currency=INR, value=5] false true true 1 Correct
  • B Coin@1b6d false false false 2
  • C Coin[currency=INR, value=5] true true true 1
  • D Coin[INR, 5] false true true 1
Correct Answer: Option A

Records generate Object's three key methods from their components, so they work correctly in hash collections.

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