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