1/*
2 ************************************************************************************
3 * Copyright (C) 2007-2010, Google Inc, International Business Machines Corporation *
4 * and others. All Rights Reserved.                                                 *
5 ************************************************************************************
6 */
7package com.ibm.icu.impl;
8
9import java.util.Comparator;
10import java.util.Iterator;
11
12public class IterableComparator<T> implements Comparator<Iterable<T>> {
13    private final Comparator<T> comparator;
14    private final int shorterFirst; // = 1 for shorter first, -1 otherwise
15
16    public IterableComparator() {
17        this(null, true);
18    }
19
20    public IterableComparator(Comparator<T> comparator) {
21        this(comparator, true);
22    }
23
24    public IterableComparator(Comparator<T> comparator, boolean shorterFirst) {
25        this.comparator = comparator;
26        this.shorterFirst = shorterFirst ? 1 : -1;
27    }
28
29    public int compare(Iterable<T> a, Iterable<T> b) {
30        if (a == null) {
31            return b == null ? 0 : -shorterFirst;
32        } else if (b == null) {
33            return shorterFirst;
34        }
35        Iterator<T> ai = a.iterator();
36        Iterator<T> bi = b.iterator();
37        while (true) {
38            if (!ai.hasNext()) {
39                return bi.hasNext() ? -shorterFirst : 0;
40            }
41            if (!bi.hasNext()) {
42                return shorterFirst;
43            }
44            T aItem = ai.next();
45            T bItem = bi.next();
46            @SuppressWarnings("unchecked")
47            int result = comparator != null ? comparator.compare(aItem, bItem) : ((Comparable<T>)aItem).compareTo(bItem);
48            if (result != 0) {
49                return result;
50            }
51        }
52    }
53
54    @SuppressWarnings("unchecked")
55    public static <T> int compareIterables(Iterable<T> a, Iterable<T> b) {
56        return NOCOMPARATOR.compare(a, b);
57    }
58
59    @SuppressWarnings("rawtypes")
60    private static final IterableComparator NOCOMPARATOR = new IterableComparator();
61}