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 /** An ordering that uses the reverse of the natural order of the values. */ 25 @GwtCompatible(serializable = true) 26 @SuppressWarnings("unchecked") // TODO: the right way to explain this?? 27 final class ReverseNaturalOrdering 28 extends Ordering<Comparable> implements Serializable { 29 static final ReverseNaturalOrdering INSTANCE = new ReverseNaturalOrdering(); 30 31 public int compare(Comparable left, Comparable right) { 32 checkNotNull(left); // right null is caught later 33 if (left == right) { 34 return 0; 35 } 36 37 @SuppressWarnings("unchecked") // we're permitted to throw CCE 38 int result = right.compareTo(left); 39 return result; 40 } 41 42 @Override public <S extends Comparable> Ordering<S> reverse() { 43 return Ordering.natural(); 44 } 45 46 // Override the six min/max methods to "hoist" delegation outside loops 47 48 @Override public <E extends Comparable> E min(E a, E b) { 49 return NaturalOrdering.INSTANCE.max(a, b); 50 } 51 52 @Override public <E extends Comparable> E min(E a, E b, E c, E... rest) { 53 return NaturalOrdering.INSTANCE.max(a, b, c, rest); 54 } 55 56 @Override public <E extends Comparable> E min(Iterable<E> iterable) { 57 return NaturalOrdering.INSTANCE.max(iterable); 58 } 59 60 @Override public <E extends Comparable> E max(E a, E b) { 61 return NaturalOrdering.INSTANCE.min(a, b); 62 } 63 64 @Override public <E extends Comparable> E max(E a, E b, E c, E... rest) { 65 return NaturalOrdering.INSTANCE.min(a, b, c, rest); 66 } 67 68 @Override public <E extends Comparable> E max(Iterable<E> iterable) { 69 return NaturalOrdering.INSTANCE.min(iterable); 70 } 71 72 // preserving singleton-ness gives equals()/hashCode() for free 73 private Object readResolve() { 74 return INSTANCE; 75 } 76 77 @Override public String toString() { 78 return "Ordering.natural().reverse()"; 79 } 80 81 private ReverseNaturalOrdering() {} 82 83 private static final long serialVersionUID = 0; 84 } 85