ProgrammingVery hardProduct-company placement · Java

What is printed?

What is printed?
TreeSet<Integer> s = new TreeSet<>(List.of(5, 1, 9, 3, 7));
System.out.print(s.headSet(5) + " " + s.tailSet(5) + " "
    + s.descendingSet().first() + " " + s.pollFirst() + " " + s);
  1. A. [1, 3] [5, 7, 9] 9 1 [3, 5, 7, 9]
  2. B. [1, 3, 5] [5, 7, 9] 9 1 [3, 5, 7, 9]
  3. C. [1, 3] [5, 7, 9] 1 1 [3, 5, 7, 9]
  4. D. [1, 3] [5, 7, 9] 9 1 [1, 3, 5, 7, 9]

Correct answer: A. [1, 3] [5, 7, 9] 9 1 [3, 5, 7, 9]

headSet(to) excludes the bound, tailSet(from) includes it. descendingSet().first() is the largest element. pollFirst removes 1, and since + evaluates left to right the final s is printed after that removal.

More OOP with C++ and Java questions

Exams that ask this topic