Posts

Showing posts from June, 2023

Java : What You Should Know about the Comparable and Comparator Interfaces

  Comparable Comparator Interface Implemented by the class being compared Separate interface Purpose Defines natural ordering for the class Defines custom ordering for objects Method compareTo(Object obj): int compare(T obj1, T obj2): int Use Case Sorting objects based on inherent properties Sorting objects based on custom criteria Usage Objects implement Comparable interface Custom Comparator instances are created Sorting Single sorting criterion Multiple sorting criteria Control Class has control over its own ordering No control over the class being compared Dependency Objects must be modified to implement Comparable Objects can be sorted without modification Ret...