Skills101
← All practice quizzes

Quiz: Comparable vs Comparator

5 questions · new set on every retakeNo time limitPass: 60%+10 XP on first pass

Sort your own objects correctly. The compareTo contract, Comparable for natural order, Comparator.comparing with thenComparing and reversed, null handling, the subtraction overflow bug, and why TreeSet can lose your data.

Log in to take the quiz

Free account · see your score, answers and explanations, earn XP

  1. Question 1

    What does a negative return value from compare(a, b) mean?

  2. Question 2

    What does this print?

    import java.util.*;
    public class Main {
        public static void main(String[] args) {
            List<String> w = new ArrayList<>(List.of("kiwi", "fig", "apple", "date"));
            w.sort(Comparator.comparingInt(String::length).thenComparing(Comparator.naturalOrder()));
            System.out.println(w);
        }
    }
    
  3. Question 3

    Which interface would you implement INSIDE a class to give it a natural order?

  4. Question 4

    Why is return a.price - b.price; a risky compare method for int prices?

  5. Question 5

    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());
        }
    }
    
🎯 Today’s placement challenge — 10 questions, no login. Can you score 10/10?Take today’s challenge →