Search code examples
javaoopcomparatorcomparable

Writing a default Comparator class in Java


I am implementing a generic heap class in Java. There are two constructors for this class, one is the default constructor with no parameters. The other one takes in a comparator object that the user can pass in so that the user can control how the elements of a heap are compared. Now if the user uses the default constructor, I want my class to use to default comparator object. The compare method of this object simply calls the compareTo() method (part of the Comparable interface). Is there a way to do this and if so, how?


Solution

  • I guess a generic comparator would look like that:

    public class ComparableComparator<T extends Comparable<T>> implements Comparator<T> {
      @Override
      public int compare(T lhs, T rhs) {
        return lhs.compareTo(rhs);
      }  
    }