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