Search code examples
javacollectionstreemap

in case of TreeMap , if pass our own class object as key then which interface is needed to be implemented Comparable or Comparator and why?


In case of "TreeMap" , if pass our own class object as key then which interface is needed to be implemented Comparable or Comparator and why?


Solution

  • If you construct the TreeMap specifying a comparator, then that will be used to compare the keys.

    If you construct the TreeMap without specifying a comparator, then the keys must implement Comparable.

    Typically the key would implement Comparable if there's a natural ordering, but you'd use a separate class as a Comparator for some custom ordering, or if there is no natural ordering for the key type. It would be unusual for the key type to implement Comparator itself.