beginnerCollections Framework
What is the difference between Comparable and Comparator in Java?
Comparable is implemented by the class itself via compareTo(), defining one single 'natural' ordering (e.g., a Product sorting by its own ID); Comparator is a separate object implementing compare(a, b), letting you define multiple, external, interchangeable orderings for the same class (e.g., sort Products by price, then by name) without modifying the class itself.
Ready to master this question?
Generate a complete walkthrough ā background, the full answer in plain language, a working code example explained line by line, a real-world scenario, common mistakes, and how this same question gets asked in different ways.
Sign in to generate a response