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