View Javadoc
1   /*
2    * Copyright (C) 2010 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.base;
18  
19  import static com.google.common.base.Preconditions.checkNotNull;
20  
21  import com.google.common.annotations.Beta;
22  import com.google.common.annotations.GwtCompatible;
23  
24  import java.io.Serializable;
25  
26  import javax.annotation.Nullable;
27  
28  /**
29   * A strategy for determining whether two instances are considered equivalent. Examples of
30   * equivalences are the {@linkplain #identity() identity equivalence} and {@linkplain #equals equals
31   * equivalence}.
32   *
33   * @author Bob Lee
34   * @author Ben Yu
35   * @author Gregory Kick
36   * @since 10.0 (<a href="http://code.google.com/p/guava-libraries/wiki/Compatibility"
37   *        >mostly source-compatible</a> since 4.0)
38   */
39  @GwtCompatible
40  public abstract class Equivalence<T> {
41    /**
42     * Constructor for use by subclasses.
43     */
44    protected Equivalence() {}
45  
46    /**
47     * Returns {@code true} if the given objects are considered equivalent.
48     *
49     * <p>The {@code equivalent} method implements an equivalence relation on object references:
50     *
51     * <ul>
52     * <li>It is <i>reflexive</i>: for any reference {@code x}, including null, {@code
53     *     equivalent(x, x)} returns {@code true}.
54     * <li>It is <i>symmetric</i>: for any references {@code x} and {@code y}, {@code
55     *     equivalent(x, y) == equivalent(y, x)}.
56     * <li>It is <i>transitive</i>: for any references {@code x}, {@code y}, and {@code z}, if
57     *     {@code equivalent(x, y)} returns {@code true} and {@code equivalent(y, z)} returns {@code
58     *     true}, then {@code equivalent(x, z)} returns {@code true}.
59     * <li>It is <i>consistent</i>: for any references {@code x} and {@code y}, multiple invocations
60     *     of {@code equivalent(x, y)} consistently return {@code true} or consistently return {@code
61     *     false} (provided that neither {@code x} nor {@code y} is modified).
62     * </ul>
63     */
64    public final boolean equivalent(@Nullable T a, @Nullable T b) {
65      if (a == b) {
66        return true;
67      }
68      if (a == null || b == null) {
69        return false;
70      }
71      return doEquivalent(a, b);
72    }
73  
74    /**
75     * Returns {@code true} if {@code a} and {@code b} are considered equivalent.
76     *
77     * <p>Called by {@link #equivalent}. {@code a} and {@code b} are not the same
78     * object and are not nulls.
79     *
80     * @since 10.0 (previously, subclasses would override equivalent())
81     */
82    protected abstract boolean doEquivalent(T a, T b);
83  
84    /**
85     * Returns a hash code for {@code t}.
86     *
87     * <p>The {@code hash} has the following properties:
88     * <ul>
89     * <li>It is <i>consistent</i>: for any reference {@code x}, multiple invocations of
90     *     {@code hash(x}} consistently return the same value provided {@code x} remains unchanged
91     *     according to the definition of the equivalence. The hash need not remain consistent from
92     *     one execution of an application to another execution of the same application.
93     * <li>It is <i>distributable across equivalence</i>: for any references {@code x} and {@code y},
94     *     if {@code equivalent(x, y)}, then {@code hash(x) == hash(y)}. It is <i>not</i> necessary
95     *     that the hash be distributable across <i>inequivalence</i>. If {@code equivalence(x, y)}
96     *     is false, {@code hash(x) == hash(y)} may still be true.
97     * <li>{@code hash(null)} is {@code 0}.
98     * </ul>
99     */
100   public final int hash(@Nullable T t) {
101     if (t == null) {
102       return 0;
103     }
104     return doHash(t);
105   }
106 
107   /**
108    * Returns a hash code for non-null object {@code t}.
109    *
110    * <p>Called by {@link #hash}.
111    *
112    * @since 10.0 (previously, subclasses would override hash())
113    */
114   protected abstract int doHash(T t);
115 
116   /**
117    * Returns a new equivalence relation for {@code F} which evaluates equivalence by first applying
118    * {@code function} to the argument, then evaluating using {@code this}. That is, for any pair of
119    * non-null objects {@code x} and {@code y}, {@code
120    * equivalence.onResultOf(function).equivalent(a, b)} is true if and only if {@code
121    * equivalence.equivalent(function.apply(a), function.apply(b))} is true.
122    *
123    * <p>For example:
124    *
125    * <pre>   {@code
126    *    Equivalence<Person> SAME_AGE = Equivalence.equals().onResultOf(GET_PERSON_AGE);}</pre>
127    * 
128    * <p>{@code function} will never be invoked with a null value.
129    * 
130    * <p>Note that {@code function} must be consistent according to {@code this} equivalence
131    * relation. That is, invoking {@link Function#apply} multiple times for a given value must return
132    * equivalent results.
133    * For example, {@code Equivalence.identity().onResultOf(Functions.toStringFunction())} is broken
134    * because it's not guaranteed that {@link Object#toString}) always returns the same string
135    * instance.
136    * 
137    * @since 10.0
138    */
139   public final <F> Equivalence<F> onResultOf(Function<F, ? extends T> function) {
140     return new FunctionalEquivalence<F, T>(function, this);
141   }
142   
143   /**
144    * Returns a wrapper of {@code reference} that implements
145    * {@link Wrapper#equals(Object) Object.equals()} such that
146    * {@code wrap(a).equals(wrap(b))} if and only if {@code equivalent(a, b)}.
147    * 
148    * @since 10.0
149    */
150   public final <S extends T> Wrapper<S> wrap(@Nullable S reference) {
151     return new Wrapper<S>(this, reference);
152   }
153 
154   /**
155    * Wraps an object so that {@link #equals(Object)} and {@link #hashCode()} delegate to an
156    * {@link Equivalence}.
157    *
158    * <p>For example, given an {@link Equivalence} for {@link String strings} named {@code equiv}
159    * that tests equivalence using their lengths:
160    *
161    * <pre>   {@code
162    *   equiv.wrap("a").equals(equiv.wrap("b")) // true
163    *   equiv.wrap("a").equals(equiv.wrap("hello")) // false}</pre>
164    *
165    * <p>Note in particular that an equivalence wrapper is never equal to the object it wraps.
166    *
167    * <pre>   {@code
168    *   equiv.wrap(obj).equals(obj) // always false}</pre>
169    *
170    * @since 10.0
171    */
172   public static final class Wrapper<T> implements Serializable {
173     private final Equivalence<? super T> equivalence;
174     @Nullable private final T reference;
175 
176     private Wrapper(Equivalence<? super T> equivalence, @Nullable T reference) {
177       this.equivalence = checkNotNull(equivalence);
178       this.reference = reference;
179     }
180 
181     /** Returns the (possibly null) reference wrapped by this instance. */
182     @Nullable public T get() {
183       return reference;
184     }
185 
186     /**
187      * Returns {@code true} if {@link Equivalence#equivalent(Object, Object)} applied to the wrapped
188      * references is {@code true} and both wrappers use the {@link Object#equals(Object) same}
189      * equivalence.
190      */
191     @Override public boolean equals(@Nullable Object obj) {
192       if (obj == this) {
193         return true;
194       }
195       if (obj instanceof Wrapper) {
196         Wrapper<?> that = (Wrapper<?>) obj; // note: not necessarily a Wrapper<T>
197 
198         if (this.equivalence.equals(that.equivalence)) {
199           /*
200            * We'll accept that as sufficient "proof" that either equivalence should be able to
201            * handle either reference, so it's safe to circumvent compile-time type checking.
202            */
203           @SuppressWarnings("unchecked")
204           Equivalence<Object> equivalence = (Equivalence<Object>) this.equivalence;
205           return equivalence.equivalent(this.reference, that.reference);
206         }
207       }
208       return false;
209     }
210 
211     /**
212      * Returns the result of {@link Equivalence#hash(Object)} applied to the wrapped reference.
213      */
214     @Override public int hashCode() {
215       return equivalence.hash(reference);
216     }
217 
218     /**
219      * Returns a string representation for this equivalence wrapper. The form of this string
220      * representation is not specified.
221      */
222     @Override public String toString() {
223       return equivalence + ".wrap(" + reference + ")";
224     }
225 
226     private static final long serialVersionUID = 0;
227   }
228 
229   /**
230    * Returns an equivalence over iterables based on the equivalence of their elements.  More
231    * specifically, two iterables are considered equivalent if they both contain the same number of
232    * elements, and each pair of corresponding elements is equivalent according to
233    * {@code this}.  Null iterables are equivalent to one another.
234    * 
235    * <p>Note that this method performs a similar function for equivalences as {@link
236    * com.google.common.collect.Ordering#lexicographical} does for orderings.
237    *
238    * @since 10.0
239    */
240   @GwtCompatible(serializable = true)
241   public final <S extends T> Equivalence<Iterable<S>> pairwise() {
242     // Ideally, the returned equivalence would support Iterable<? extends T>. However,
243     // the need for this is so rare that it's not worth making callers deal with the ugly wildcard.
244     return new PairwiseEquivalence<S>(this);
245   }
246   
247   /**
248    * Returns a predicate that evaluates to true if and only if the input is
249    * equivalent to {@code target} according to this equivalence relation.
250    * 
251    * @since 10.0
252    */
253   @Beta
254   public final Predicate<T> equivalentTo(@Nullable T target) {
255     return new EquivalentToPredicate<T>(this, target);
256   }
257 
258   private static final class EquivalentToPredicate<T> implements Predicate<T>, Serializable {
259 
260     private final Equivalence<T> equivalence;
261     @Nullable private final T target;
262 
263     EquivalentToPredicate(Equivalence<T> equivalence, @Nullable T target) {
264       this.equivalence = checkNotNull(equivalence);
265       this.target = target;
266     }
267 
268     @Override public boolean apply(@Nullable T input) {
269       return equivalence.equivalent(input, target);
270     }
271 
272     @Override public boolean equals(@Nullable Object obj) {
273       if (this == obj) {
274         return true;
275       }
276       if (obj instanceof EquivalentToPredicate) {
277         EquivalentToPredicate<?> that = (EquivalentToPredicate<?>) obj;
278         return equivalence.equals(that.equivalence)
279             && Objects.equal(target, that.target);
280       }
281       return false;
282     }
283 
284     @Override public int hashCode() {
285       return Objects.hashCode(equivalence, target);
286     }
287 
288     @Override public String toString() {
289       return equivalence + ".equivalentTo(" + target + ")";
290     }
291 
292     private static final long serialVersionUID = 0;
293   }
294 
295   /**
296    * Returns an equivalence that delegates to {@link Object#equals} and {@link Object#hashCode}.
297    * {@link Equivalence#equivalent} returns {@code true} if both values are null, or if neither
298    * value is null and {@link Object#equals} returns {@code true}. {@link Equivalence#hash} returns
299    * {@code 0} if passed a null value.
300    *
301    * @since 13.0
302    * @since 8.0 (in Equivalences with null-friendly behavior)
303    * @since 4.0 (in Equivalences)
304    */
305   public static Equivalence<Object> equals() {
306     return Equals.INSTANCE;
307   }
308 
309   /**
310    * Returns an equivalence that uses {@code ==} to compare values and {@link
311    * System#identityHashCode(Object)} to compute the hash code.  {@link Equivalence#equivalent}
312    * returns {@code true} if {@code a == b}, including in the case that a and b are both null.
313    *
314    * @since 13.0
315    * @since 4.0 (in Equivalences)
316    */
317   public static Equivalence<Object> identity() {
318     return Identity.INSTANCE;
319   }
320 
321   static final class Equals extends Equivalence<Object>
322       implements Serializable {
323     
324     static final Equals INSTANCE = new Equals();
325 
326     @Override protected boolean doEquivalent(Object a, Object b) {
327       return a.equals(b);
328     }
329     @Override public int doHash(Object o) {
330       return o.hashCode();
331     }
332 
333     private Object readResolve() {
334       return INSTANCE;
335     } 
336     private static final long serialVersionUID = 1;
337   }
338   
339   static final class Identity extends Equivalence<Object>
340       implements Serializable {
341     
342     static final Identity INSTANCE = new Identity();
343     
344     @Override protected boolean doEquivalent(Object a, Object b) {
345       return false;
346     }
347 
348     @Override protected int doHash(Object o) {
349       return System.identityHashCode(o);
350     }
351  
352     private Object readResolve() {
353       return INSTANCE;
354     }
355     private static final long serialVersionUID = 1;
356   }
357 }