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
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();
you could make the comparator as a parameter of Plane
public class Plane implements Comparable<Plane> {
private Comparable<Plane> c;
public Plane(Comparable<Plane> c) {
this.c = c;
}
@Override
public int compareTo(Plane another) {
return c.compareTo(another);
}
}
whenever you want to change the compare method,just pass a diffferent Comparable instance or a lambda expression to the constructor
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.