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.List; 26 27/** An ordering that uses the natural order of the values. */ 28@GwtCompatible(serializable = true) 29@SuppressWarnings("unchecked") // TODO(kevinb): the right way to explain this?? 30final class NaturalOrdering 31 extends Ordering<Comparable> implements Serializable { 32 static final NaturalOrdering INSTANCE = new NaturalOrdering(); 33 34 @Override public int compare(Comparable left, Comparable right) { 35 checkNotNull(left); // for GWT 36 checkNotNull(right); 37 if (left == right) { 38 return 0; 39 } 40 41 return left.compareTo(right); 42 } 43 44 @Override public <S extends Comparable> Ordering<S> reverse() { 45 return (Ordering<S>) ReverseNaturalOrdering.INSTANCE; 46 } 47 48 // Override to remove a level of indirection from inner loop 49 @Override public int binarySearch( 50 List<? extends Comparable> sortedList, Comparable key) { 51 return Collections.binarySearch((List) sortedList, key); 52 } 53 54 // Override to remove a level of indirection from inner loop 55 @Override public <E extends Comparable> List<E> sortedCopy( 56 Iterable<E> iterable) { 57 List<E> list = Lists.newArrayList(iterable); 58 Collections.sort(list); 59 return list; 60 } 61 62 // preserving singleton-ness gives equals()/hashCode() for free 63 private Object readResolve() { 64 return INSTANCE; 65 } 66 67 @Override public String toString() { 68 return "Ordering.natural()"; 69 } 70 71 private NaturalOrdering() {} 72 73 private static final long serialVersionUID = 0; 74} 75