1/*
2 * Copyright (C) 2011 The Guava Authors
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5 * in compliance with the License. You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software distributed under the
10 * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
11 * express or implied. See the License for the specific language governing permissions and
12 * limitations under the License.
13 */
14
15package com.google.common.collect;
16
17import static com.google.common.base.Preconditions.checkNotNull;
18
19import com.google.common.annotations.GwtCompatible;
20
21import java.util.Comparator;
22import java.util.SortedSet;
23
24/**
25 * Utilities for dealing with sorted collections of all types.
26 *
27 * @author Louis Wasserman
28 */
29@GwtCompatible
30final class SortedIterables {
31  private SortedIterables() {}
32
33  /**
34   * Returns {@code true} if {@code elements} is a sorted collection using an ordering equivalent
35   * to {@code comparator}.
36   */
37  public static boolean hasSameComparator(Comparator<?> comparator, Iterable<?> elements) {
38    checkNotNull(comparator);
39    checkNotNull(elements);
40    Comparator<?> comparator2;
41    if (elements instanceof SortedSet) {
42      comparator2 = comparator((SortedSet<?>) elements);
43    } else if (elements instanceof SortedIterable) {
44      comparator2 = ((SortedIterable<?>) elements).comparator();
45    } else {
46      return false;
47    }
48    return comparator.equals(comparator2);
49  }
50
51  @SuppressWarnings("unchecked")
52  // if sortedSet.comparator() is null, the set must be naturally ordered
53  public static <E> Comparator<? super E> comparator(SortedSet<E> sortedSet) {
54    Comparator<? super E> result = sortedSet.comparator();
55    if (result == null) {
56      result = (Comparator<? super E>) Ordering.natural();
57    }
58    return result;
59  }
60}
61