我需要用 Java 实现几个比较器。
我有很多已知的类,A1
、A2
、A3
、...、An
,它们都扩展了类 A
。我想要的是一个基于 Guava Ordering
的比较器类,如下所示:
Ordering<A> sorterType1 = new Ordering<A>() {
// Here, provide a Set or something similar that keeps in memory
// the class types and the associated priority.
@Override
public int compare(A left, A right) {
// return -1 if class of left has an higher priority wrt class of right;
// return 0 if class of left has the same priority wrt class of right;
// return 1, otherwise.
}
由于我需要开发很多不同的比较器,因此我不想将优先级放在类类型中,因为每个比较器都有多个不同的优先级。 我缺少的是带有注释的部分。
带注释的部分最有效、最高效的实现方式是什么?
最佳答案
不要自己编写比较实现,请使用Ordering
超能力(准确地说是Ordering#explicit(List)
):
List<Class<? extends A>> myOrder = ImmutableList.of(
A1.class, A4.class, A3.class, A2.class);
Ordering<A> explicitByClassOrdering = Ordering.explicit(myOrder)
.onResultOf(new Function<A, Class<? extends A>>() {
@Override public Class<? extends A> apply(A a) {
return a.getClass();
}
});
System.out.println(explicitByClassOrdering.sortedCopy(
ImmutableList.of(new A3(), new A2(), new A3(), new A1(), new A4())));
// [Test$A1, Test$A4, Test$A3, Test$A3, Test$A2]
关于Java 比较器通过对扩展公共(public)父类的类使用优先级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16213103/