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 static com.google.common.base.Preconditions.checkNotNull;
20  
21  import com.google.common.annotations.GwtCompatible;
22  import java.io.Serializable;
23  
24  /** An ordering that uses the natural order of the values. */
25  @GwtCompatible(serializable = true)
26  @SuppressWarnings("unchecked") // TODO(kevinb): the right way to explain this??
27  final class NaturalOrdering extends Ordering<Comparable> implements Serializable {
28    static final NaturalOrdering INSTANCE = new NaturalOrdering();
29  
30    private transient Ordering<Comparable> nullsFirst;
31    private transient Ordering<Comparable> nullsLast;
32  
33    @Override
34    public int compare(Comparable left, Comparable right) {
35      checkNotNull(left); // for GWT
36      checkNotNull(right);
37      return left.compareTo(right);
38    }
39  
40    @Override
41    public <S extends Comparable> Ordering<S> nullsFirst() {
42      Ordering<Comparable> result = nullsFirst;
43      if (result == null) {
44        result = nullsFirst = super.nullsFirst();
45      }
46      return (Ordering<S>) result;
47    }
48  
49    @Override
50    public <S extends Comparable> Ordering<S> nullsLast() {
51      Ordering<Comparable> result = nullsLast;
52      if (result == null) {
53        result = nullsLast = super.nullsLast();
54      }
55      return (Ordering<S>) result;
56    }
57  
58    @Override
59    public <S extends Comparable> Ordering<S> reverse() {
60      return (Ordering<S>) ReverseNaturalOrdering.INSTANCE;
61    }
62  
63    // preserving singleton-ness gives equals()/hashCode() for free
64    private Object readResolve() {
65      return INSTANCE;
66    }
67  
68    @Override
69    public String toString() {
70      return "Ordering.natural()";
71    }
72  
73    private NaturalOrdering() {}
74  
75    private static final long serialVersionUID = 0;
76  }