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