简体   繁体   English

如何使我自己的通用结构具有动态比较器

[英]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我想知道如何覆盖实现 Comparable 的 class 中的 compareTo 方法

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和使用该结构的 class 是看起来像那样的平面

public class Plane implements Comparable<Plane> 

with override compareTo method,使用覆盖 compareTo 方法,

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?但我想要另一个带有平面和不同 compareTo 方法的树结构,我如何在平面上覆盖该方法?

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.然后在树元素上使用比较器而不是compareTo方法。


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).但请注意,提供比较器的能力消除了T extends Comparable<T>的限制(这更好,因为T extends Comparable<? super T>无论如何)。

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 工厂方法来创建一个自然排序的树:

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您可以将比较器作为 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每当您想更改比较方法时,只需将不同的 Comparable 实例或 lambda 表达式传递给构造函数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM