ProgrammingVery hardProduct-company placement · Java

What is printed?

What is printed?
BigDecimal a = new BigDecimal("1.0"), b = new BigDecimal("1.00");
Set<BigDecimal> h = new HashSet<>(List.of(a, b));
Set<BigDecimal> t = new TreeSet<>(List.of(a, b));
System.out.print(h.size() + " " + t.size() + " " + a.equals(b) + " " + a.compareTo(b));
  1. A. 1 1 true 0
  2. B. 2 2 false 0
  3. C. 1 2 false 1
  4. D. 2 1 false 0

Correct answer: D. 2 1 false 0

BigDecimal.equals also compares scale (1.0 vs 1.00 differ), but compareTo compares numeric value only (0). HashSet uses equals/hashCode and keeps both; TreeSet uses compareTo and treats them as duplicates.

More OOP with C++ and Java questions

Exams that ask this topic