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));- A. 1 1 true 0
- B. 2 2 false 0
- C. 1 2 false 1
- 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
- What is printed? java Stream.of("a", "bb", "ccc") .filter(s -> { System.out.print("f" + s.length()); return s.length() > 1; }) .map(s -> {…
- What is printed? java Stream.of(1, 2, 3).peek(System.out::print).map(x -> x 2); System.out.print("end");
- What is printed? java Map<Integer, Long> m = Stream.of("a", "bb", "cc", "ddd", "e") .collect(Collectors.groupingBy(String::length…
- What is printed? java Map<Integer, String> m = Stream.of("ab", "cd", "e") .collect(Collectors.toMap(String::length, s -> s))…
- Why is the comparator (a, b) -> a - b unsafe for sorting arbitrary int values in Java?
- What is printed? java String s = "ab"; StringBuilder sb = new StringBuilder("ab"); System.out.print(s.equals(sb) + " " +…