Collections · interview question
Which interface should a class implement to define its natural ordering, so that Collections.sort(list) works without a comparator?
Fill in the blankEasy
Answer and explanation
Correct answer
Comparable or Comparable<T> or java.lang.Comparable
Why
Comparable<T> has one method, compareTo. For orderings other than the natural one, pass a Comparator, e.g. Comparator.comparing(Person::age).
References
Test yourself on Collections
A free test with instant, explained results. No account needed.
More Collections questions
- Why do teams use a HashSet over a List when storing items in production code?
- Which Java collection should you use if you need to store elements with fast random access and allow duplicates?
- Which collection does not allow duplicate elements?
- Which Java collection would you choose if you need to maintain insertion order and allow duplicates?
- How would you explain a key advantage of using a HashMap over a TreeMap in an interview?
- You are tasked with designing a cache system in Java where both insertion order and fast access are crucial. Which…