2 *******************************************************************************
3 * Copyright (C) 2002-2009, International Business Machines Corporation and *
4 * others. All Rights Reserved. *
5 *******************************************************************************
7 package com.ibm.icu.dev.test.util;
8 import java.util.Comparator;
10 public 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);
16 private Comparator[] comparators;
17 private int[] reordering;
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;
28 if (this.reordering.length != this.comparators.length) {
29 throw new IllegalArgumentException("comparator and reordering lengths must match");
34 public ArrayComparator (Comparator... comparators) {
35 this(comparators,null);
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)
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;
58 static class CatchExceptionComparator implements Comparator {
59 private Comparator other;
61 public CatchExceptionComparator(Comparator other) {
65 public int compare(Object arg0, Object arg1) throws RuntimeException {
67 return other.compare(arg0, arg1);
68 } catch (RuntimeException e) {
69 System.out.println("Arg0: " + arg0);
70 System.out.println("Arg1: " + arg1);