1 /* 2 * Copyright (C) 2011 The Guava Authors 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5 * in compliance with the License. You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software distributed under the License 10 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 11 * or implied. See the License for the specific language governing permissions and limitations under 12 * the License. 13 */ 14 15 package com.google.common.base; 16 17 import static com.google.common.base.Preconditions.checkNotNull; 18 19 import com.google.common.annotations.Beta; 20 import com.google.common.annotations.GwtCompatible; 21 import java.io.Serializable; 22 import javax.annotation.CheckForNull; 23 import org.checkerframework.checker.nullness.qual.Nullable; 24 25 /** 26 * Equivalence applied on functional result. 27 * 28 * @author Bob Lee 29 * @since 10.0 30 */ 31 @Beta 32 @GwtCompatible 33 @ElementTypesAreNonnullByDefault 34 final class FunctionalEquivalence<F, T> extends Equivalence<F> implements Serializable { 35 36 private static final long serialVersionUID = 0; 37 38 private final Function<? super F, ? extends @Nullable T> function; 39 private final Equivalence<T> resultEquivalence; 40 FunctionalEquivalence( Function<? super F, ? extends @Nullable T> function, Equivalence<T> resultEquivalence)41 FunctionalEquivalence( 42 Function<? super F, ? extends @Nullable T> function, Equivalence<T> resultEquivalence) { 43 this.function = checkNotNull(function); 44 this.resultEquivalence = checkNotNull(resultEquivalence); 45 } 46 47 @Override doEquivalent(F a, F b)48 protected boolean doEquivalent(F a, F b) { 49 return resultEquivalence.equivalent(function.apply(a), function.apply(b)); 50 } 51 52 @Override doHash(F a)53 protected int doHash(F a) { 54 return resultEquivalence.hash(function.apply(a)); 55 } 56 57 @Override equals(@heckForNull Object obj)58 public boolean equals(@CheckForNull Object obj) { 59 if (obj == this) { 60 return true; 61 } 62 if (obj instanceof FunctionalEquivalence) { 63 FunctionalEquivalence<?, ?> that = (FunctionalEquivalence<?, ?>) obj; 64 return function.equals(that.function) && resultEquivalence.equals(that.resultEquivalence); 65 } 66 return false; 67 } 68 69 @Override hashCode()70 public int hashCode() { 71 return Objects.hashCode(function, resultEquivalence); 72 } 73 74 @Override toString()75 public String toString() { 76 return resultEquivalence + ".onResultOf(" + function + ")"; 77 } 78 } 79