summaryrefslogtreecommitdiff
path: root/android_icu4j/src/main/java/android/icu/impl/IterableComparator.java
blob: f3e7685e4240691ead167e2863271b409bfb6231 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/* GENERATED SOURCE. DO NOT MODIFY. */
/*
 ************************************************************************************
 * Copyright (C) 2007-2015, Google Inc, International Business Machines Corporation
 * and others. All Rights Reserved.
 ************************************************************************************
 */
package android.icu.impl;

import java.util.Comparator;
import java.util.Iterator;

/**
 * TODO: Move to android.icu.dev.somewhere.
 * 2015-sep-03: Not used in ICU but used in CLDR and in UnicodeTools.
 * @hide Only a subset of ICU is exposed in Android
 * @hide All android.icu classes are currently hidden
 */
public class IterableComparator<T> implements Comparator<Iterable<T>> {
    private final Comparator<T> comparator;
    private final int shorterFirst; // = 1 for shorter first, -1 otherwise

    public IterableComparator() {
        this(null, true);
    }

    public IterableComparator(Comparator<T> comparator) {
        this(comparator, true);
    }

    public IterableComparator(Comparator<T> comparator, boolean shorterFirst) {
        this.comparator = comparator;
        this.shorterFirst = shorterFirst ? 1 : -1;
    }

    public int compare(Iterable<T> a, Iterable<T> b) {
        if (a == null) {
            return b == null ? 0 : -shorterFirst;
        } else if (b == null) {
            return shorterFirst;
        }
        Iterator<T> ai = a.iterator();
        Iterator<T> bi = b.iterator();
        while (true) {
            if (!ai.hasNext()) {
                return bi.hasNext() ? -shorterFirst : 0;
            }
            if (!bi.hasNext()) {
                return shorterFirst;
            }
            T aItem = ai.next();
            T bItem = bi.next();
            @SuppressWarnings("unchecked")
            int result = comparator != null ? comparator.compare(aItem, bItem) : ((Comparable<T>)aItem).compareTo(bItem);
            if (result != 0) {
                return result;
            }
        }
    }

    @SuppressWarnings("unchecked")
    public static <T> int compareIterables(Iterable<T> a, Iterable<T> b) {
        return NOCOMPARATOR.compare(a, b);
    }

    @SuppressWarnings("rawtypes")
    private static final IterableComparator NOCOMPARATOR = new IterableComparator();
}