• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
17 package com.google.common.collect;
18 
19 import static com.google.common.base.Preconditions.checkNotNull;
20 
21 import com.google.common.annotations.GwtCompatible;
22 
23 import java.io.Serializable;
24 import java.util.Collections;
25 import java.util.Comparator;
26 import java.util.List;
27 
28 import javax.annotation.Nullable;
29 
30 /** An ordering for a pre-existing comparator. */
31 @GwtCompatible(serializable = true)
32 final class ComparatorOrdering<T> extends Ordering<T> implements Serializable {
33   final Comparator<T> comparator;
34 
ComparatorOrdering(Comparator<T> comparator)35   ComparatorOrdering(Comparator<T> comparator) {
36     this.comparator = checkNotNull(comparator);
37   }
38 
compare(T a, T b)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
binarySearch(List<? extends T> sortedList, T key)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
sortedCopy(Iterable<E> iterable)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 
equals(@ullable Object object)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 
hashCode()66   @Override public int hashCode() {
67     return comparator.hashCode();
68   }
69 
toString()70   @Override public String toString() {
71     return comparator.toString();
72   }
73 
74   private static final long serialVersionUID = 0;
75 }
76