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