2 ************************************************************************************
3 * Copyright (C) 2007-2010, Google Inc, International Business Machines Corporation *
4 * and others. All Rights Reserved. *
5 ************************************************************************************
7 package com.ibm.icu.impl;
9 import java.util.Comparator;
10 import java.util.Iterator;
12 public class IterableComparator<T> implements Comparator<Iterable<T>> {
13 private final Comparator<T> comparator;
14 private final int shorterFirst; // = 1 for shorter first, -1 otherwise
16 public IterableComparator() {
20 public IterableComparator(Comparator<T> comparator) {
21 this(comparator, true);
24 public IterableComparator(Comparator<T> comparator, boolean shorterFirst) {
25 this.comparator = comparator;
26 this.shorterFirst = shorterFirst ? 1 : -1;
29 public int compare(Iterable<T> a, Iterable<T> b) {
31 return b == null ? 0 : -shorterFirst;
32 } else if (b == null) {
35 Iterator<T> ai = a.iterator();
36 Iterator<T> bi = b.iterator();
39 return bi.hasNext() ? -shorterFirst : 0;
46 @SuppressWarnings("unchecked")
47 int result = comparator != null ? comparator.compare(aItem, bItem) : ((Comparable<T>)aItem).compareTo(bItem);
54 @SuppressWarnings("unchecked")
55 public static <T> int compareIterables(Iterable<T> a, Iterable<T> b) {
56 return NOCOMPARATOR.compare(a, b);
59 @SuppressWarnings("rawtypes")
60 private static final IterableComparator NOCOMPARATOR = new IterableComparator();