• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 java.util.Arrays;
22 import java.util.Comparator;
23 import javax.annotation.CheckForNull;
24 import org.checkerframework.checker.nullness.qual.Nullable;
25 
26 /** An ordering that tries several comparators in order. */
27 @GwtCompatible(serializable = true)
28 @ElementTypesAreNonnullByDefault
29 final class CompoundOrdering<T extends @Nullable Object> extends Ordering<T>
30     implements Serializable {
31   final Comparator<? super T>[] comparators;
32 
CompoundOrdering(Comparator<? super T> primary, Comparator<? super T> secondary)33   CompoundOrdering(Comparator<? super T> primary, Comparator<? super T> secondary) {
34     this.comparators = (Comparator<? super T>[]) new Comparator[] {primary, secondary};
35   }
36 
CompoundOrdering(Iterable<? extends Comparator<? super T>> comparators)37   CompoundOrdering(Iterable<? extends Comparator<? super T>> comparators) {
38     this.comparators = Iterables.toArray(comparators, new Comparator[0]);
39   }
40 
41   @Override
compare(@arametricNullness T left, @ParametricNullness T right)42   public int compare(@ParametricNullness T left, @ParametricNullness T right) {
43     for (int i = 0; i < comparators.length; i++) {
44       int result = comparators[i].compare(left, right);
45       if (result != 0) {
46         return result;
47       }
48     }
49     return 0;
50   }
51 
52   @Override
equals(@heckForNull Object object)53   public boolean equals(@CheckForNull Object object) {
54     if (object == this) {
55       return true;
56     }
57     if (object instanceof CompoundOrdering) {
58       CompoundOrdering<?> that = (CompoundOrdering<?>) object;
59       return Arrays.equals(this.comparators, that.comparators);
60     }
61     return false;
62   }
63 
64   @Override
hashCode()65   public int hashCode() {
66     return Arrays.hashCode(comparators);
67   }
68 
69   @Override
toString()70   public String toString() {
71     return "Ordering.compound(" + Arrays.toString(comparators) + ")";
72   }
73 
74   private static final long serialVersionUID = 0;
75 }
76