• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* GENERATED SOURCE. DO NOT MODIFY. */
2 // © 2016 and later: Unicode, Inc. and others.
3 // License & terms of use: http://www.unicode.org/copyright.html#License
4 /*
5  ************************************************************************************
6  * Copyright (C) 2007-2015, Google Inc, International Business Machines Corporation
7  * and others. All Rights Reserved.
8  ************************************************************************************
9  */
10 package ohos.global.icu.impl;
11 
12 import java.util.Comparator;
13 import java.util.Iterator;
14 
15 /**
16  * TODO: Move to ohos.global.icu.dev.somewhere.
17  * 2015-sep-03: Not used in ICU but used in CLDR and in UnicodeTools.
18  * @hide exposed on OHOS
19  */
20 public class IterableComparator<T> implements Comparator<Iterable<T>> {
21     private final Comparator<T> comparator;
22     private final int shorterFirst; // = 1 for shorter first, -1 otherwise
23 
IterableComparator()24     public IterableComparator() {
25         this(null, true);
26     }
27 
IterableComparator(Comparator<T> comparator)28     public IterableComparator(Comparator<T> comparator) {
29         this(comparator, true);
30     }
31 
IterableComparator(Comparator<T> comparator, boolean shorterFirst)32     public IterableComparator(Comparator<T> comparator, boolean shorterFirst) {
33         this.comparator = comparator;
34         this.shorterFirst = shorterFirst ? 1 : -1;
35     }
36 
37     @Override
compare(Iterable<T> a, Iterable<T> b)38     public int compare(Iterable<T> a, Iterable<T> b) {
39         if (a == null) {
40             return b == null ? 0 : -shorterFirst;
41         } else if (b == null) {
42             return shorterFirst;
43         }
44         Iterator<T> ai = a.iterator();
45         Iterator<T> bi = b.iterator();
46         while (true) {
47             if (!ai.hasNext()) {
48                 return bi.hasNext() ? -shorterFirst : 0;
49             }
50             if (!bi.hasNext()) {
51                 return shorterFirst;
52             }
53             T aItem = ai.next();
54             T bItem = bi.next();
55             @SuppressWarnings("unchecked")
56             int result = comparator != null ? comparator.compare(aItem, bItem) : ((Comparable<T>)aItem).compareTo(bItem);
57             if (result != 0) {
58                 return result;
59             }
60         }
61     }
62 
63     @SuppressWarnings("unchecked")
compareIterables(Iterable<T> a, Iterable<T> b)64     public static <T> int compareIterables(Iterable<T> a, Iterable<T> b) {
65         return NOCOMPARATOR.compare(a, b);
66     }
67 
68     @SuppressWarnings("rawtypes")
69     private static final IterableComparator NOCOMPARATOR = new IterableComparator();
70 }