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 com.google.common.annotations.GwtCompatible; 20 21import java.io.Serializable; 22 23import javax.annotation.Nullable; 24 25/** An ordering that treats {@code null} as greater than all other values. */ 26@GwtCompatible(serializable = true) 27final class NullsLastOrdering<T> extends Ordering<T> implements Serializable { 28 final Ordering<? super T> ordering; 29 30 NullsLastOrdering(Ordering<? super T> ordering) { 31 this.ordering = ordering; 32 } 33 34 @Override public int compare(@Nullable T left, @Nullable T right) { 35 if (left == right) { 36 return 0; 37 } 38 if (left == null) { 39 return LEFT_IS_GREATER; 40 } 41 if (right == null) { 42 return RIGHT_IS_GREATER; 43 } 44 return ordering.compare(left, right); 45 } 46 47 @Override public <S extends T> Ordering<S> reverse() { 48 // ordering.reverse() might be optimized, so let it do its thing 49 return ordering.reverse().nullsFirst(); 50 } 51 52 @Override public <S extends T> Ordering<S> nullsFirst() { 53 return ordering.nullsFirst(); 54 } 55 56 @SuppressWarnings("unchecked") // still need the right way to explain this 57 @Override public <S extends T> Ordering<S> nullsLast() { 58 return (Ordering<S>) this; 59 } 60 61 @Override public boolean equals(@Nullable Object object) { 62 if (object == this) { 63 return true; 64 } 65 if (object instanceof NullsLastOrdering) { 66 NullsLastOrdering<?> that = (NullsLastOrdering<?>) object; 67 return this.ordering.equals(that.ordering); 68 } 69 return false; 70 } 71 72 @Override public int hashCode() { 73 return ordering.hashCode() ^ -921210296; // meaningless 74 } 75 76 @Override public String toString() { 77 return ordering + ".nullsLast()"; 78 } 79 80 private static final long serialVersionUID = 0; 81} 82