Home | History | Annotate | Download | only in collect
      1 /*
      2  * Copyright (C) 2007 Google Inc.
      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 com.google.common.annotations.GwtCompatible;
     20 import static com.google.common.base.Preconditions.checkNotNull;
     21 
     22 import java.io.Serializable;
     23 import java.util.Collections;
     24 import java.util.Comparator;
     25 import java.util.List;
     26 
     27 import javax.annotation.Nullable;
     28 
     29 /** An ordering for a pre-existing {@code comparator}. */
     30 @GwtCompatible(serializable = true)
     31 final class ComparatorOrdering<T> extends Ordering<T> implements Serializable {
     32   final Comparator<T> comparator;
     33 
     34   ComparatorOrdering(Comparator<T> comparator) {
     35     this.comparator = checkNotNull(comparator);
     36   }
     37 
     38   public int compare(T a, T b) {
     39     return comparator.compare(a, b);
     40   }
     41 
     42   // Override just to remove a level of indirection from inner loops
     43   @Override public int binarySearch(List<? extends T> sortedList, T key) {
     44     return Collections.binarySearch(sortedList, key, comparator);
     45   }
     46 
     47   // Override just to remove a level of indirection from inner loops
     48   @Override public <E extends T> List<E> sortedCopy(Iterable<E> iterable) {
     49     List<E> list = Lists.newArrayList(iterable);
     50     Collections.sort(list, comparator);
     51     return list;
     52   }
     53 
     54   @Override public boolean equals(@Nullable Object object) {
     55     if (object == this) {
     56       return true;
     57     }
     58     if (object instanceof ComparatorOrdering) {
     59       ComparatorOrdering<?> that = (ComparatorOrdering<?>) object;
     60       return this.comparator.equals(that.comparator);
     61     }
     62     return false;
     63   }
     64 
     65   @Override public int hashCode() {
     66     return comparator.hashCode();
     67   }
     68 
     69   @Override public String toString() {
     70     return comparator.toString();
     71   }
     72 
     73   private static final long serialVersionUID = 0;
     74 }
     75