🎙 Free live masterclass · Sun, 29 Nov, 7:00 pm IST · Java Full Stack roadmap Register free →
Skills101
← 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());
    }
}
  1. A.3
  2. B.2
  3. C.1
  4. 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 →