• 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 
21 import java.io.Serializable;
22 import java.util.Comparator;
23 import java.util.List;
24 
25 /** An ordering that tries several comparators in order. */
26 @GwtCompatible(serializable = true)
27 final class CompoundOrdering<T> extends Ordering<T> implements Serializable {
28   final ImmutableList<Comparator<? super T>> comparators;
29 
CompoundOrdering(Comparator<? super T> primary, Comparator<? super T> secondary)30   CompoundOrdering(Comparator<? super T> primary,
31       Comparator<? super T> secondary) {
32     this.comparators
33         = ImmutableList.<Comparator<? super T>>of(primary, secondary);
34   }
35 
CompoundOrdering(Iterable<? extends Comparator<? super T>> comparators)36   CompoundOrdering(Iterable<? extends Comparator<? super T>> comparators) {
37     this.comparators = ImmutableList.copyOf(comparators);
38   }
39 
CompoundOrdering(List<? extends Comparator<? super T>> comparators, Comparator<? super T> lastComparator)40   CompoundOrdering(List<? extends Comparator<? super T>> comparators,
41       Comparator<? super T> lastComparator) {
42     this.comparators = new ImmutableList.Builder<Comparator<? super T>>()
43         .addAll(comparators).add(lastComparator).build();
44   }
45 
compare(T left, T right)46   @Override public int compare(T left, T right) {
47     for (Comparator<? super T> comparator : comparators) {
48       int result = comparator.compare(left, right);
49       if (result != 0) {
50         return result;
51       }
52     }
53     return 0;
54   }
55 
equals(Object object)56   @Override public boolean equals(Object object) {
57     if (object == this) {
58       return true;
59     }
60     if (object instanceof CompoundOrdering) {
61       CompoundOrdering<?> that = (CompoundOrdering<?>) object;
62       return this.comparators.equals(that.comparators);
63     }
64     return false;
65   }
66 
hashCode()67   @Override public int hashCode() {
68     return comparators.hashCode();
69   }
70 
toString()71   @Override public String toString() {
72     return "Ordering.compound(" + comparators + ")";
73   }
74 
75   private static final long serialVersionUID = 0;
76 }
77