Swiftorial Logo
Home
Swift Lessons
AI Tools
Learn More
Career
Resources

Java FAQ: Top Questions

22. What is the Comparable and Comparator interfaces?

Comparable and Comparator are interfaces in Java used for sorting objects, defined in java.lang and java.util , respectively.

  • Comparable:
    • Implemented by a class to define its natural ordering (e.g., String , Integer ).
    • Has one method: compareTo(T o) .
    • Used by Collections.sort or Arrays.sort .
  • Comparator:
    • A separate class or lambda for custom sorting.
    • Has method: compare(T o1, T o2) .
    • Provides flexibility for multiple sorting criteria without modifying the class.