001/*
002 * Copyright (C) 2010 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
005 * in compliance with the License. You may obtain a copy of the License at
006 *
007 * http://www.apache.org/licenses/LICENSE-2.0
008 *
009 * Unless required by applicable law or agreed to in writing, software distributed under the License
010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
011 * or implied. See the License for the specific language governing permissions and limitations under
012 * the License.
013 */
014
015package com.google.common.base;
016
017import static com.google.common.base.Preconditions.checkNotNull;
018
019import com.google.common.annotations.GwtCompatible;
020import com.google.errorprone.annotations.ForOverride;
021import java.io.Serializable;
022import java.util.function.BiPredicate;
023import javax.annotation.Nullable;
024
025/**
026 * A strategy for determining whether two instances are considered equivalent, and for computing
027 * hash codes in a manner consistent with that equivalence. Two examples of equivalences are the
028 * {@linkplain #identity() identity equivalence} and the {@linkplain #equals "equals" equivalence}.
029 *
030 * @author Bob Lee
031 * @author Ben Yu
032 * @author Gregory Kick
033 * @since 10.0 (<a href="https://github.com/google/guava/wiki/Compatibility">mostly
034 *     source-compatible</a> since 4.0)
035 */
036@GwtCompatible
037public abstract class Equivalence<T> implements BiPredicate<T, T> {
038  /**
039   * Constructor for use by subclasses.
040   */
041  protected Equivalence() {}
042
043  /**
044   * Returns {@code true} if the given objects are considered equivalent.
045   *
046   * <p>This method describes an <i>equivalence relation</i> on object references, meaning that for
047   * all references {@code x}, {@code y}, and {@code z} (any of which may be null):
048   *
049   * <ul>
050   * <li>{@code equivalent(x, x)} is true (<i>reflexive</i> property)
051   * <li>{@code equivalent(x, y)} and {@code equivalent(y, x)} each return the same result
052   *     (<i>symmetric</i> property)
053   * <li>If {@code equivalent(x, y)} and {@code equivalent(y, z)} are both true, then
054   *     {@code equivalent(x, z)} is also true (<i>transitive</i> property)
055   * </ul>
056   *
057   * <p>Note that all calls to {@code equivalent(x, y)} are expected to return the same result as
058   * long as neither {@code x} nor {@code y} is modified.
059   */
060  public final boolean equivalent(@Nullable T a, @Nullable T b) {
061    if (a == b) {
062      return true;
063    }
064    if (a == null || b == null) {
065      return false;
066    }
067    return doEquivalent(a, b);
068  }
069
070  /**
071   * @deprecated Provided only to satisfy the {@link BiPredicate} interface; use
072   *     {@link #equivalent} instead.
073   * @since 21.0
074   */
075  @Deprecated
076  @Override
077  public final boolean test(@Nullable T t, @Nullable T u) {
078    return equivalent(t, u);
079  }
080
081  /**
082   * Implemented by the user to determine whether {@code a} and {@code b} are considered
083   * equivalent, subject to the requirements specified in {@link #equivalent}.
084   *
085   * <p>This method should not be called except by {@link #equivalent}. When {@link #equivalent}
086   * calls this method, {@code a} and {@code b} are guaranteed to be distinct, non-null instances.
087   *
088   * @since 10.0 (previously, subclasses would override equivalent())
089   */
090  @ForOverride
091  protected abstract boolean doEquivalent(T a, T b);
092
093  /**
094   * Returns a hash code for {@code t}.
095   *
096   * <p>The {@code hash} has the following properties:
097   * <ul>
098   * <li>It is <i>consistent</i>: for any reference {@code x}, multiple invocations of
099   *     {@code hash(x}} consistently return the same value provided {@code x} remains unchanged
100   *     according to the definition of the equivalence. The hash need not remain consistent from
101   *     one execution of an application to another execution of the same application.
102   * <li>It is <i>distributable across equivalence</i>: for any references {@code x} and {@code y},
103   *     if {@code equivalent(x, y)}, then {@code hash(x) == hash(y)}. It is <i>not</i> necessary
104   *     that the hash be distributable across <i>inequivalence</i>. If {@code equivalence(x, y)} is
105   *     false, {@code hash(x) == hash(y)} may still be true.
106   * <li>{@code hash(null)} is {@code 0}.
107   * </ul>
108   */
109  public final int hash(@Nullable T t) {
110    if (t == null) {
111      return 0;
112    }
113    return doHash(t);
114  }
115
116  /**
117   * Implemented by the user to return a hash code for {@code t}, subject to the requirements
118   * specified in {@link #hash}.
119   *
120   * <p>This method should not be called except by {@link #hash}. When {@link #hash} calls this
121   * method, {@code t} is guaranteed to be non-null.
122   *
123   * @since 10.0 (previously, subclasses would override hash())
124   */
125  @ForOverride
126  protected abstract int doHash(T t);
127
128  /**
129   * Returns a new equivalence relation for {@code F} which evaluates equivalence by first applying
130   * {@code function} to the argument, then evaluating using {@code this}. That is, for any pair of
131   * non-null objects {@code x} and {@code y}, {@code
132   * equivalence.onResultOf(function).equivalent(a, b)} is true if and only if {@code
133   * equivalence.equivalent(function.apply(a), function.apply(b))} is true.
134   *
135   * <p>For example:
136   *
137   * <pre>   {@code
138   *    Equivalence<Person> SAME_AGE = Equivalence.equals().onResultOf(GET_PERSON_AGE);}</pre>
139   *
140   * <p>{@code function} will never be invoked with a null value.
141   *
142   * <p>Note that {@code function} must be consistent according to {@code this} equivalence
143   * relation. That is, invoking {@link Function#apply} multiple times for a given value must return
144   * equivalent results. For example,
145   * {@code Equivalence.identity().onResultOf(Functions.toStringFunction())} is broken because it's
146   * not guaranteed that {@link Object#toString}) always returns the same string instance.
147   *
148   * @since 10.0
149   */
150  public final <F> Equivalence<F> onResultOf(Function<F, ? extends T> function) {
151    return new FunctionalEquivalence<F, T>(function, this);
152  }
153
154  /**
155   * Returns a wrapper of {@code reference} that implements {@link Wrapper#equals(Object)
156   * Object.equals()} such that {@code wrap(a).equals(wrap(b))} if and only if
157   * {@code equivalent(a, b)}.
158   *
159   * @since 10.0
160   */
161  public final <S extends T> Wrapper<S> wrap(@Nullable S reference) {
162    return new Wrapper<S>(this, reference);
163  }
164
165  /**
166   * Wraps an object so that {@link #equals(Object)} and {@link #hashCode()} delegate to an
167   * {@link Equivalence}.
168   *
169   * <p>For example, given an {@link Equivalence} for {@link String strings} named {@code equiv}
170   * that tests equivalence using their lengths:
171   *
172   * <pre>   {@code
173   *   equiv.wrap("a").equals(equiv.wrap("b")) // true
174   *   equiv.wrap("a").equals(equiv.wrap("hello")) // false}</pre>
175   *
176   * <p>Note in particular that an equivalence wrapper is never equal to the object it wraps.
177   *
178   * <pre>   {@code
179   *   equiv.wrap(obj).equals(obj) // always false}</pre>
180   *
181   * @since 10.0
182   */
183  public static final class Wrapper<T> implements Serializable {
184    private final Equivalence<? super T> equivalence;
185    @Nullable private final T reference;
186
187    private Wrapper(Equivalence<? super T> equivalence, @Nullable T reference) {
188      this.equivalence = checkNotNull(equivalence);
189      this.reference = reference;
190    }
191
192    /** Returns the (possibly null) reference wrapped by this instance. */
193    @Nullable
194    public T get() {
195      return reference;
196    }
197
198    /**
199     * Returns {@code true} if {@link Equivalence#equivalent(Object, Object)} applied to the wrapped
200     * references is {@code true} and both wrappers use the {@link Object#equals(Object) same}
201     * equivalence.
202     */
203    @Override
204    public boolean equals(@Nullable Object obj) {
205      if (obj == this) {
206        return true;
207      }
208      if (obj instanceof Wrapper) {
209        Wrapper<?> that = (Wrapper<?>) obj; // note: not necessarily a Wrapper<T>
210
211        if (this.equivalence.equals(that.equivalence)) {
212          /*
213           * We'll accept that as sufficient "proof" that either equivalence should be able to
214           * handle either reference, so it's safe to circumvent compile-time type checking.
215           */
216          @SuppressWarnings("unchecked")
217          Equivalence<Object> equivalence = (Equivalence<Object>) this.equivalence;
218          return equivalence.equivalent(this.reference, that.reference);
219        }
220      }
221      return false;
222    }
223
224    /**
225     * Returns the result of {@link Equivalence#hash(Object)} applied to the wrapped reference.
226     */
227    @Override
228    public int hashCode() {
229      return equivalence.hash(reference);
230    }
231
232    /**
233     * Returns a string representation for this equivalence wrapper. The form of this string
234     * representation is not specified.
235     */
236    @Override
237    public String toString() {
238      return equivalence + ".wrap(" + reference + ")";
239    }
240
241    private static final long serialVersionUID = 0;
242  }
243
244  /**
245   * Returns an equivalence over iterables based on the equivalence of their elements. More
246   * specifically, two iterables are considered equivalent if they both contain the same number of
247   * elements, and each pair of corresponding elements is equivalent according to {@code this}. Null
248   * iterables are equivalent to one another.
249   *
250   * <p>Note that this method performs a similar function for equivalences as
251   * {@link com.google.common.collect.Ordering#lexicographical} does for orderings.
252   *
253   * @since 10.0
254   */
255  @GwtCompatible(serializable = true)
256  public final <S extends T> Equivalence<Iterable<S>> pairwise() {
257    // Ideally, the returned equivalence would support Iterable<? extends T>. However,
258    // the need for this is so rare that it's not worth making callers deal with the ugly wildcard.
259    return new PairwiseEquivalence<S>(this);
260  }
261
262  /**
263   * Returns a predicate that evaluates to true if and only if the input is equivalent to {@code
264   * target} according to this equivalence relation.
265   *
266   * @since 10.0
267   */
268  public final Predicate<T> equivalentTo(@Nullable T target) {
269    return new EquivalentToPredicate<T>(this, target);
270  }
271
272  private static final class EquivalentToPredicate<T> implements Predicate<T>, Serializable {
273
274    private final Equivalence<T> equivalence;
275    @Nullable private final T target;
276
277    EquivalentToPredicate(Equivalence<T> equivalence, @Nullable T target) {
278      this.equivalence = checkNotNull(equivalence);
279      this.target = target;
280    }
281
282    @Override
283    public boolean apply(@Nullable T input) {
284      return equivalence.equivalent(input, target);
285    }
286
287    @Override
288    public boolean equals(@Nullable Object obj) {
289      if (this == obj) {
290        return true;
291      }
292      if (obj instanceof EquivalentToPredicate) {
293        EquivalentToPredicate<?> that = (EquivalentToPredicate<?>) obj;
294        return equivalence.equals(that.equivalence) && Objects.equal(target, that.target);
295      }
296      return false;
297    }
298
299    @Override
300    public int hashCode() {
301      return Objects.hashCode(equivalence, target);
302    }
303
304    @Override
305    public String toString() {
306      return equivalence + ".equivalentTo(" + target + ")";
307    }
308
309    private static final long serialVersionUID = 0;
310  }
311
312  /**
313   * Returns an equivalence that delegates to {@link Object#equals} and {@link Object#hashCode}.
314   * {@link Equivalence#equivalent} returns {@code true} if both values are null, or if neither
315   * value is null and {@link Object#equals} returns {@code true}. {@link Equivalence#hash} returns
316   * {@code 0} if passed a null value.
317   *
318   * @since 13.0
319   * @since 8.0 (in Equivalences with null-friendly behavior)
320   * @since 4.0 (in Equivalences)
321   */
322  public static Equivalence<Object> equals() {
323    return Equals.INSTANCE;
324  }
325
326  /**
327   * Returns an equivalence that uses {@code ==} to compare values and
328   * {@link System#identityHashCode(Object)} to compute the hash code.
329   * {@link Equivalence#equivalent} returns {@code true} if {@code a == b}, including in the case
330   * that a and b are both null.
331   *
332   * @since 13.0
333   * @since 4.0 (in Equivalences)
334   */
335  public static Equivalence<Object> identity() {
336    return Identity.INSTANCE;
337  }
338
339  static final class Equals extends Equivalence<Object> implements Serializable {
340
341    static final Equals INSTANCE = new Equals();
342
343    @Override
344    protected boolean doEquivalent(Object a, Object b) {
345      return a.equals(b);
346    }
347
348    @Override
349    protected int doHash(Object o) {
350      return o.hashCode();
351    }
352
353    private Object readResolve() {
354      return INSTANCE;
355    }
356
357    private static final long serialVersionUID = 1;
358  }
359
360  static final class Identity extends Equivalence<Object> implements Serializable {
361
362    static final Identity INSTANCE = new Identity();
363
364    @Override
365    protected boolean doEquivalent(Object a, Object b) {
366      return false;
367    }
368
369    @Override
370    protected int doHash(Object o) {
371      return System.identityHashCode(o);
372    }
373
374    private Object readResolve() {
375      return INSTANCE;
376    }
377
378    private static final long serialVersionUID = 1;
379  }
380}