Java 比较器通过对扩展公共(public)父类的类使用优先级

标签 java guava comparator

我需要用 Java 实现几个比较器。

我有很多已知的类,A1A2A3、...、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/

相关文章:

java - 按 HashMap 的值(按映射的值比较)对 HashMap 的数组列表进行排序

java - Akka future list - 如何等待 future list 完成?

java - IntelliJ IDEA 可以自动给方法调用填充变量吗?

java - 获取三重副本时的值错误

java - 在 JFileChooser 中仅显示 TSTA* 文件

Java 随机访问映射

java - collections.sort 没有对 arraylist 进行排序

java - 在 Java 中实例化 BiMap 的 google-collections

java - 如何在 junit 测试中测试 Comparator