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

mat*_*boy 0 java comparator guava

我需要在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.
        }
Run Code Online (Sandbox Code Playgroud)

由于我需要开发许多不同的比较器,我不想将优先级放在类类型中,因为每个比较器有几个不同的优先级.我缺少的是带注释的部分.

具有注释的部件的最有效和最有效的实施是什么?

Xae*_*ess 6

不要自己写比较实现,使用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]
Run Code Online (Sandbox Code Playgroud)

  • 非常优雅的解决方案. (2认同)