← Quiz: Comparable vs Comparator: all 10 questions
Quiz: Comparable vs Comparator · Question 5 of 10
What does this print? (code)
What does this print?
import java.util.*;
public class Main {
public static void main(String[] args) {
Set<String> s = new TreeSet<>(Comparator.comparingInt(String::length));
s.add("cat");
s.add("dog");
s.add("horse");
System.out.println(s.size());
}
}
- A.3
- B.2
- C.1
- D.Compile error
Answer & explanation
Correct answer: 2
"dog" has the same length as "cat", so compare returns 0 and the TreeSet treats it as a duplicate.
Can you get the rest right without peeking?
Take the timed Quiz: Comparable vs Comparator quiz free. Pass it to earn XP and count towards your certificate.
Start the quiz →