ComparatorOrdering.java revision 1d580d0f6ee4f21eb309ba7b509d2c6d671c4044
1/*
2 * Copyright (C) 2007 The Guava Authors
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.google.common.collect;
18
19import static com.google.common.base.Preconditions.checkNotNull;
20
21import com.google.common.annotations.GwtCompatible;
22
23import java.io.Serializable;
24import java.util.Collections;
25import java.util.Comparator;
26import java.util.List;
27
28import javax.annotation.Nullable;
29
30/** An ordering for a pre-existing comparator. */
31@GwtCompatible(serializable = true)
32final class ComparatorOrdering<T> extends Ordering<T> implements Serializable {
33  final Comparator<T> comparator;
34
35  ComparatorOrdering(Comparator<T> comparator) {
36    this.comparator = checkNotNull(comparator);
37  }
38
39  @Override public int compare(T a, T b) {
40    return comparator.compare(a, b);
41  }
42
43  // Override just to remove a level of indirection from inner loops
44  @Override public int binarySearch(List<? extends T> sortedList, T key) {
45    return Collections.binarySearch(sortedList, key, comparator);
46  }
47
48  // Override just to remove a level of indirection from inner loops
49  @Override public <E extends T> List<E> sortedCopy(Iterable<E> iterable) {
50    List<E> list = Lists.newArrayList(iterable);
51    Collections.sort(list, comparator);
52    return list;
53  }
54
55  @Override public boolean equals(@Nullable Object object) {
56    if (object == this) {
57      return true;
58    }
59    if (object instanceof ComparatorOrdering) {
60      ComparatorOrdering<?> that = (ComparatorOrdering<?>) object;
61      return this.comparator.equals(that.comparator);
62    }
63    return false;
64  }
65
66  @Override public int hashCode() {
67    return comparator.hashCode();
68  }
69
70  @Override public String toString() {
71    return comparator.toString();
72  }
73
74  private static final long serialVersionUID = 0;
75}
76