ProgrammingModerateAmazon/Microsoft SDE MCQ · Java placement

What is printed?

What is printed?
record Pt(int x, int y) { }
// in main:
Set<Pt> s = new HashSet<>();
s.add(new Pt(1, 2));
s.add(new Pt(1, 2));
s.add(new Pt(2, 1));
System.out.print(s.size() + " " + new Pt(1, 2).equals(new Pt(1, 2)));
  1. A. 3 false
  2. B. 2 false
  3. C. 3 true
  4. D. 2 true

Correct answer: D. 2 true

A record gets equals and hashCode derived from all of its components, so the two Pt(1, 2) objects are equal and the set holds 2 elements. Pt(2, 1) differs in component order.

More OOP with C++ and Java questions

Exams that ask this topic