QuizzesComparable & Comparator — Concept Check
intermediate
java

Comparable & Comparator — Concept Check

Questions on Comparable & Comparator. Define natural ordering with Comparable and flexible multi-field sorting with Comparator — the two pillars of Java sorting.

7 minutes 7 questions Pass at 70%
Time Limit
7 minutes - timer starts when you begin
Change Answers Freely
Revisit and change any answer before submitting
Full Review After Submit
Correct answers and explanations shown for every question
Auto-submit on timeout
Quiz submits automatically when time runs out

Questions in this quiz

7 questions on Comparable & Comparator — Concept Check. Work through them here, then start the quiz to answer them and see your score.

  1. 1.You have a class `Task` with fields `priority` and `name`. You want to sort a list of tasks by priority ascending, then by name alphabetically. Which approach should you use?

    • AUse Collections.sort() without implementing Comparable or Comparator
    • BImplement both Comparable and Comparator
    • CImplement Comparable and override compareTo() in Task
    • DUse a Comparator with comparing() and thenComparing()
  2. 2.A developer uses `Collections.sort()` on a list of custom objects without implementing Comparable or providing a Comparator. What will happen?

    • AThe code will not compile
    • BThe list will remain unsorted
    • CThe code will compile but throw a runtime exception
    • DThe list will sort in natural order
  3. 3.Which statement about the Comparator API in Java 8 is true?

    • AComparator is less flexible than Comparable
    • BComparator can only sort by one field at a time
    • CComparator allows sorting with multiple fields using chaining methods
    • DComparator requires modifying the class to define order
  4. 4.What is a potential issue when using `a - b` for integer comparison in compareTo()?

    • AIt is not compatible with Comparator
    • BIt is always less efficient
    • CIt may cause integer overflow
    • DIt cannot compare negative numbers
  5. 5.Why might you choose Comparator over Comparable for sorting?

    • ATo simplify the code by avoiding external objects
    • BTo increase performance by avoiding method calls
    • CTo ensure a single natural order for the class
    • DTo define multiple sorting orders without modifying the class
  6. 6.Given a list of products, how would you find the one with the highest rating using a Comparator?

    • AUse Collections.max(products, byRating)
    • BUse products.stream().max(Comparator.comparingDouble(Product::rating))
    • CUse products.stream().sorted(byRating).findFirst()
    • DUse products.stream().min(byRating.reversed())
  7. 7.Which of the following is a valid reason to implement Comparable in a class?

    • ATo avoid using Comparator
    • BTo allow multiple sorting strategies
    • CTo define a natural order for the class
    • DTo improve sorting performance