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.List; 22 import javax.annotation.CheckForNull; 23 24 /** An ordering that compares objects according to a given order. */ 25 @GwtCompatible(serializable = true) 26 @ElementTypesAreNonnullByDefault 27 final class ExplicitOrdering<T> extends Ordering<T> implements Serializable { 28 final ImmutableMap<T, Integer> rankMap; 29 ExplicitOrdering(List<T> valuesInOrder)30 ExplicitOrdering(List<T> valuesInOrder) { 31 this(Maps.indexMap(valuesInOrder)); 32 } 33 ExplicitOrdering(ImmutableMap<T, Integer> rankMap)34 ExplicitOrdering(ImmutableMap<T, Integer> rankMap) { 35 this.rankMap = rankMap; 36 } 37 38 @Override compare(T left, T right)39 public int compare(T left, T right) { 40 return rank(left) - rank(right); // safe because both are nonnegative 41 } 42 rank(T value)43 private int rank(T value) { 44 Integer rank = rankMap.get(value); 45 if (rank == null) { 46 throw new IncomparableValueException(value); 47 } 48 return rank; 49 } 50 51 @Override equals(@heckForNull Object object)52 public boolean equals(@CheckForNull Object object) { 53 if (object instanceof ExplicitOrdering) { 54 ExplicitOrdering<?> that = (ExplicitOrdering<?>) object; 55 return this.rankMap.equals(that.rankMap); 56 } 57 return false; 58 } 59 60 @Override hashCode()61 public int hashCode() { 62 return rankMap.hashCode(); 63 } 64 65 @Override toString()66 public String toString() { 67 return "Ordering.explicit(" + rankMap.keySet() + ")"; 68 } 69 70 private static final long serialVersionUID = 0; 71 } 72