ProgrammingVery hardProduct-company placement · Java

What is printed?

What is printed?
Set<String> s = new TreeSet<>(Comparator.comparingInt(String::length));
s.add("one"); s.add("two"); s.add("three"); s.add("four");
System.out.print(s);
  1. A. [one, four, three]
  2. B. [four, one, three, two]
  3. C. [one, two, four, three]
  4. D. [two, four, three]

Correct answer: A. [one, four, three]

A TreeSet decides duplicates with its comparator, not equals: "two" compares as 0 against "one" (both length 3), so it is not added. The rest are ordered by length 3, 4, 5.

More OOP with C++ and Java questions

Exams that ask this topic