What is the purpose of the `Comparable` vs `Comparator` interface in Java?

Java Associate Hard

Java Associate — Hard

What is the purpose of the `Comparable` vs `Comparator` interface in Java?

Key points

  • Comparable defines natural ordering within the class; Comparator allows for custom comparison logic
  • Comparable uses `compareTo()`; Comparator uses `compare()`
  • Comparable is implemented by the class itself; Comparator is implemented externally
  • Comparable is used for natural ordering; Comparator is used for custom ordering

Ready to go further?

Related questions