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 @Override 14 public int compare(Object o1, Object o2) { 15 return ((Comparable) o1).compareTo(o2); 16 } 17 }; 18 private Comparator[] comparators; 19 private int[] reordering; 20 ArrayComparator(Comparator[] comparators, int[] reordering)21 public ArrayComparator(Comparator[] comparators, int[] reordering) { 22 this.comparators = comparators; 23 this.reordering = reordering; 24 if (this.reordering == null) { 25 this.reordering = new int[comparators.length]; 26 for (int i = 0; i < this.reordering.length; ++i) { 27 this.reordering[i] = i; 28 } 29 } else { 30 if (this.reordering.length != this.comparators.length) { 31 throw new IllegalArgumentException("comparator and reordering lengths must match"); 32 } 33 } 34 } 35 ArrayComparator(Comparator... comparators)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 @Override compare(Object a0, Object a1)46 public int compare(Object a0, Object a1) { 47 Object[] arg0 = (Object[]) a0; 48 Object[] arg1 = (Object[]) a1; 49 for (int j = 0; j < comparators.length; ++j) { 50 int i = reordering[j]; 51 Comparator comp = comparators[i]; 52 if (comp == null) continue; 53 int result = comp.compare(arg0[i], arg1[i]); 54 if (result == 0) continue; 55 if (result > 0) return i + 1; 56 return -(i + 1); 57 } 58 return 0; 59 } 60 61 static class CatchExceptionComparator implements Comparator { 62 private Comparator other; 63 CatchExceptionComparator(Comparator other)64 public CatchExceptionComparator(Comparator other) { 65 this.other = other; 66 } 67 68 @Override compare(Object arg0, Object arg1)69 public int compare(Object arg0, Object arg1) throws RuntimeException { 70 try { 71 return other.compare(arg0, arg1); 72 } catch (RuntimeException e) { 73 System.out.println("Arg0: " + arg0); 74 System.out.println("Arg1: " + arg1); 75 throw e; 76 } 77 } 78 } 79 80 }