ArrayComparator.java revision 7935b1839a081ed19ae0d33029ad3c09632a2caa
1/*
2 *******************************************************************************
3 * Copyright (C) 2002-2012, International Business Machines Corporation and    *
4 * others. All Rights Reserved.                                                *
5 *******************************************************************************
6 */
7package com.ibm.icu.dev.util;
8import java.util.Comparator;
9
10public class ArrayComparator implements Comparator {
11    public static final Comparator COMPARABLE = new Comparator() {
12        public int compare(Object o1, Object o2) {
13            return ((Comparable)o1).compareTo(o2);
14        }
15    };
16    private Comparator[] comparators;
17    private int[] reordering;
18
19    public ArrayComparator (Comparator[] comparators, int[] reordering) {
20        this.comparators = comparators;
21        this.reordering = reordering;
22        if (this.reordering == null) {
23            this.reordering = new int[comparators.length];
24            for (int i = 0; i < this.reordering.length; ++i) {
25                this.reordering[i] = i;
26            }
27        } else {
28            if (this.reordering.length != this.comparators.length) {
29                throw new IllegalArgumentException("comparator and reordering lengths must match");
30            }
31        }
32    }
33
34    public ArrayComparator (Comparator... comparators) {
35        this(comparators,null);
36    }
37
38    /* Lexigraphic compare. Returns the first difference
39     * @return zero if equal. Otherwise +/- (i+1)
40     * where i is the index of the first comparator finding a difference
41     * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
42     */
43    public int compare(Object a0, Object a1) {
44        Object[] arg0 = (Object[]) a0;
45        Object[] arg1 = (Object[]) a1;
46        for (int j = 0; j < comparators.length; ++j) {
47            int i = reordering[j];
48            Comparator comp = comparators[i];
49            if (comp == null) continue;
50            int result = comp.compare(arg0[i], arg1[i]);
51            if (result == 0) continue;
52            if (result > 0) return i+1;
53            return -(i+1);
54        }
55        return 0;
56    }
57
58    static class CatchExceptionComparator implements Comparator {
59        private Comparator other;
60
61        public CatchExceptionComparator(Comparator other) {
62            this.other = other;
63        }
64
65        public int compare(Object arg0, Object arg1) throws RuntimeException {
66            try {
67                return other.compare(arg0, arg1);
68            } catch (RuntimeException e) {
69                System.out.println("Arg0: " + arg0);
70                System.out.println("Arg1: " + arg1);
71                throw e;
72            }
73        }
74    }
75
76}