0

I need to implement several comparators in Java.

I have a lot of known classes, A1, A2, A3, ..., An, which all extends class A. What I want to to is a comparator class based on Guava Ordering, like the following:

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.
        }

Since I need to develop a lot of different comparators, I don't want to put the priority inside the class type, since there are several priorities differentiated for each comparator. What I'm missing are the parts with comments.

What is the most effective and efficient implementation of the parts with comments?

4

1 回答 1

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]
于 2013-04-25T11:28:37.123 回答