1 /* 2 ******************************************************************************* 3 * Copyright (C) 2002-2012, International Business Machines Corporation and * 4 * others. All Rights Reserved. * 5 ******************************************************************************* 6 */ 7 package org.unicode.cldr.util; 8 9 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 ArrayComparator(Comparator[] comparators, int[] reordering)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("comparator and reordering lengths must match"); 31 } 32 } 33 } 34 ArrayComparator(Comparator... comparators)35 public ArrayComparator(Comparator... comparators) { 36 this(comparators, null); 37 } 38 39 /* Lexigraphic compare. Returns the first difference 40 * @return zero if equal. Otherwise +/- (i+1) 41 * where i is the index of the first comparator finding a difference 42 * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object) 43 */ compare(Object a0, Object a1)44 public int compare(Object a0, Object a1) { 45 Object[] arg0 = (Object[]) a0; 46 Object[] arg1 = (Object[]) a1; 47 for (int j = 0; j < comparators.length; ++j) { 48 int i = reordering[j]; 49 Comparator comp = comparators[i]; 50 if (comp == null) continue; 51 int result = comp.compare(arg0[i], arg1[i]); 52 if (result == 0) continue; 53 if (result > 0) return i + 1; 54 return -(i + 1); 55 } 56 return 0; 57 } 58 59 static class CatchExceptionComparator implements Comparator { 60 private Comparator other; 61 CatchExceptionComparator(Comparator other)62 public CatchExceptionComparator(Comparator other) { 63 this.other = other; 64 } 65 compare(Object arg0, Object arg1)66 public int compare(Object arg0, Object arg1) throws RuntimeException { 67 try { 68 return other.compare(arg0, arg1); 69 } catch (RuntimeException e) { 70 System.out.println("Arg0: " + arg0); 71 System.out.println("Arg1: " + arg1); 72 throw e; 73 } 74 } 75 } 76 77 }