Search code examples
javacomparatorcomparable

How to make my own generic structure to have dynamic comparator


I want to know how i can override compareTo method in class which implements Comparable

my structure Tree is declared like this

public class Tree<T extends Comparable<T>> 

and class which used that structure is Plane that looks like that

public class Plane implements Comparable<Plane> 

with override compareTo method,

the thing is if i want create a tree with default comparator i can do that easily with this

Tree<Plane> planes = new Tree<Plane>();

but i want have another tree structure with planes and with different compareTo method, how i can override that method in plane?

Thanks


Solution

  • Define an overloaded constructor:

    public Tree() {
      this(Comparator.naturalOrder());
    }
    
    public Tree(Comparator<? super T> comparator) {
      this.comparator = comparator; // store in a field
    }
    

    And then use the comparator instead of the compareTo method on the tree elements.


    But note that the ability to supply a comparator removes the restriction that T extends Comparable<T> (which is better as T extends Comparable<? super T> anyway).

    But in such a case, you can't have a default constructor type-safely. You would either need to require a comparator always to be passed; or provide a static factory method to create a naturally-ordered tree:

    static <T extends Comparable<? super T>> Tree<T> withNaturalOrder() {
      return new Tree<>(Comparator.naturalOrder());
    }
    

    And invoke like

    Tree<String> tree = Tree.withNaturalOrder();