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 24 import javax.annotation.Nullable; 25 26 /** An ordering that uses the reverse of a given order. */ 27 @GwtCompatible(serializable = true) 28 final class ReverseOrdering<T> extends Ordering<T> implements Serializable { 29 final Ordering<? super T> forwardOrder; 30 31 ReverseOrdering(Ordering<? super T> forwardOrder) { 32 this.forwardOrder = checkNotNull(forwardOrder); 33 } 34 35 public int compare(T a, T b) { 36 return forwardOrder.compare(b, a); 37 } 38 39 @SuppressWarnings("unchecked") // how to explain? 40 @Override public <S extends T> Ordering<S> reverse() { 41 return (Ordering) forwardOrder; 42 } 43 44 // Override the six min/max methods to "hoist" delegation outside loops 45 46 @Override public <E extends T> E min(E a, E b) { 47 return forwardOrder.max(a, b); 48 } 49 50 @Override public <E extends T> E min(E a, E b, E c, E... rest) { 51 return forwardOrder.max(a, b, c, rest); 52 } 53 54 @Override public <E extends T> E min(Iterable<E> iterable) { 55 return forwardOrder.max(iterable); 56 } 57 58 @Override public <E extends T> E max(E a, E b) { 59 return forwardOrder.min(a, b); 60 } 61 62 @Override public <E extends T> E max(E a, E b, E c, E... rest) { 63 return forwardOrder.min(a, b, c, rest); 64 } 65 66 @Override public <E extends T> E max(Iterable<E> iterable) { 67 return forwardOrder.min(iterable); 68 } 69 70 @Override public int hashCode() { 71 return -forwardOrder.hashCode(); 72 } 73 74 @Override public boolean equals(@Nullable Object object) { 75 if (object == this) { 76 return true; 77 } 78 if (object instanceof ReverseOrdering) { 79 ReverseOrdering<?> that = (ReverseOrdering<?>) object; 80 return this.forwardOrder.equals(that.forwardOrder); 81 } 82 return false; 83 } 84 85 @Override public String toString() { 86 return forwardOrder + ".reverse()"; 87 } 88 89 private static final long serialVersionUID = 0; 90 } 91