001    /*
002     * Copyright (C) 2010 The Guava Authors
003     *
004     * Licensed under the Apache License, Version 2.0 (the "License");
005     * you may not use this file except in compliance with the License.
006     * You may obtain a copy of the License at
007     *
008     * http://www.apache.org/licenses/LICENSE-2.0
009     *
010     * Unless required by applicable law or agreed to in writing, software
011     * distributed under the License is distributed on an "AS IS" BASIS,
012     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013     * See the License for the specific language governing permissions and
014     * limitations under the License.
015     */
016    
017    package com.google.common.base;
018    
019    import static com.google.common.base.Preconditions.checkNotNull;
020    
021    import com.google.common.annotations.Beta;
022    import com.google.common.annotations.GwtCompatible;
023    
024    import java.io.Serializable;
025    
026    import javax.annotation.Nullable;
027    
028    /**
029     * A strategy for determining whether two instances are considered equivalent. Examples of
030     * equivalences are the {@link Equivalences#identity() identity equivalence} and {@link
031     * Equivalences#equals equals equivalence}.
032     *
033     * @author Bob Lee
034     * @author Ben Yu
035     * @author Gregory Kick
036     * @since 10.0 (<a href="http://code.google.com/p/guava-libraries/wiki/Compatibility"
037     *        >mostly source-compatible</a> since 4.0)
038     */
039    @GwtCompatible
040    public abstract class Equivalence<T> {
041      /**
042       * Constructor for use by subclasses.
043       */
044      protected Equivalence() {}
045    
046      /**
047       * Returns {@code true} if the given objects are considered equivalent.
048       *
049       * <p>The {@code equivalent} method implements an equivalence relation on object references:
050       *
051       * <ul>
052       * <li>It is <i>reflexive</i>: for any reference {@code x}, including null, {@code
053       *     equivalent(x, x)} returns {@code true}.
054       * <li>It is <i>symmetric</i>: for any references {@code x} and {@code y}, {@code
055       *     equivalent(x, y) == equivalent(y, x)}.
056       * <li>It is <i>transitive</i>: for any references {@code x}, {@code y}, and {@code z}, if
057       *     {@code equivalent(x, y)} returns {@code true} and {@code equivalent(y, z)} returns {@code
058       *     true}, then {@code equivalent(x, z)} returns {@code true}.
059       * <li>It is <i>consistent</i>: for any references {@code x} and {@code y}, multiple invocations
060       *     of {@code equivalent(x, y)} consistently return {@code true} or consistently return {@code
061       *     false} (provided that neither {@code x} nor {@code y} is modified).
062       * </ul>
063       */
064      public final boolean equivalent(@Nullable T a, @Nullable T b) {
065        if (a == b) {
066          return true;
067        }
068        if (a == null || b == null) {
069          return false;
070        }
071        return doEquivalent(a, b);
072      }
073    
074      /**
075       * Returns {@code true} if {@code a} and {@code b} are considered equivalent.
076       *
077       * <p>Called by {@link #equivalent}. {@code a} and {@code b} are not the same
078       * object and are not nulls.
079       *
080       * @since 10.0 (previously, subclasses would override equivalent())
081       */
082      protected abstract boolean doEquivalent(T a, T b);
083    
084      /**
085       * Returns a hash code for {@code t}.
086       *
087       * <p>The {@code hash} has the following properties:
088       * <ul>
089       * <li>It is <i>consistent</i>: for any reference {@code x}, multiple invocations of
090       *     {@code hash(x}} consistently return the same value provided {@code x} remains unchanged
091       *     according to the definition of the equivalence. The hash need not remain consistent from
092       *     one execution of an application to another execution of the same application.
093       * <li>It is <i>distributable accross equivalence</i>: for any references {@code x} and {@code y},
094       *     if {@code equivalent(x, y)}, then {@code hash(x) == hash(y)}. It is <i>not</i> necessary
095       *     that the hash be distributable accorss <i>inequivalence</i>. If {@code equivalence(x, y)}
096       *     is false, {@code hash(x) == hash(y)} may still be true.
097       * <li>{@code hash(null)} is {@code 0}.
098       * </ul>
099       */
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: <pre>   {@code
124       *
125       *    Equivalence<Person> SAME_AGE = Equivalences.equals().onResultOf(GET_PERSON_AGE);
126       * }</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 Equivalences.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(this, a).equals(wrap(this, b))} if and only if {@code this.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
164       * }</pre>
165       *
166       * <p>Note in particular that an equivalence wrapper is never equal to the object it wraps.
167       *
168       * <pre>   {@code
169       *   equiv.wrap(obj).equals(obj) // always false
170       * }</pre>
171       *
172       * @since 10.0
173       */
174      public static final class Wrapper<T> implements Serializable {
175        private final Equivalence<? super T> equivalence;
176        @Nullable private final T reference;
177    
178        private Wrapper(Equivalence<? super T> equivalence, @Nullable T reference) {
179          this.equivalence = checkNotNull(equivalence);
180          this.reference = reference;
181        }
182    
183        /** Returns the (possibly null) reference wrapped by this instance. */
184        @Nullable public T get() {
185          return reference;
186        }
187    
188        /**
189         * Returns {@code true} if {@link Equivalence#equivalent(Object, Object)} applied to the wrapped
190         * references is {@code true} and both wrappers use the {@link Object#equals(Object) same}
191         * equivalence.
192         */
193        
194        @Override
195        public boolean equals(@Nullable Object obj) {
196          if (obj == this) {
197            return true;
198          } else if (obj instanceof Wrapper) {
199            Wrapper<?> that = (Wrapper<?>) obj;
200            /*
201             * We cast to Equivalence<Object> here because we can't check the type of the reference held
202             * by the other wrapper.  But, by checking that the Equivalences are equal, we know that
203             * whatever type it is, it is assignable to the type handled by this wrapper's equivalence.
204             */
205            @SuppressWarnings("unchecked")
206            Equivalence<Object> equivalence = (Equivalence<Object>) this.equivalence;
207            return equivalence.equals(that.equivalence)
208                && equivalence.equivalent(this.reference, that.reference);
209          } else {
210            return false;
211          }
212        }
213    
214        /**
215         * Returns the result of {@link Equivalence#hash(Object)} applied to the the wrapped reference.
216         */
217        
218        @Override
219        public int hashCode() {
220          return equivalence.hash(reference);
221        }
222    
223        /**
224         * Returns a string representation for this equivalence wrapper. The form of this string
225         * representation is not specified.
226         */
227        
228        @Override
229        public String toString() {
230          return equivalence + ".wrap(" + reference + ")";
231        }
232    
233        private static final long serialVersionUID = 0;
234      }
235    
236      /**
237       * Returns an equivalence over iterables based on the equivalence of their elements.  More
238       * specifically, two iterables are considered equivalent if they both contain the same number of
239       * elements, and each pair of corresponding elements is equivalent according to
240       * {@code this}.  Null iterables are equivalent to one another.
241       * 
242       * <p>Note that this method performs a similar function for equivalences as {@link
243       * com.google.common.collect.Ordering#lexicographical} does for orderings.
244       *
245       * @since 10.0
246       */
247      @GwtCompatible(serializable = true)
248      public final <S extends T> Equivalence<Iterable<S>> pairwise() {
249        // Ideally, the returned equivalence would support Iterable<? extends T>. However,
250        // the need for this is so rare that it's not worth making callers deal with the ugly wildcard.
251        return new PairwiseEquivalence<S>(this);
252      }
253      
254      /**
255       * Returns a predicate that evaluates to true if and only if the input is
256       * equivalent to {@code target} according to this equivalence relation.
257       * 
258       * @since 10.0
259       */
260      @Beta
261      public final Predicate<T> equivalentTo(@Nullable T target) {
262        return new EquivalentToPredicate<T>(this, target);
263      }
264    
265      private static final class EquivalentToPredicate<T> implements Predicate<T>, Serializable {
266    
267        private final Equivalence<T> equivalence;
268        @Nullable private final T target;
269    
270        EquivalentToPredicate(Equivalence<T> equivalence, @Nullable T target) {
271          this.equivalence = checkNotNull(equivalence);
272          this.target = target;
273        }
274    
275        public boolean apply(@Nullable T input) {
276          return equivalence.equivalent(input, target);
277        }
278    
279        
280        @Override
281        public boolean equals(@Nullable Object obj) {
282          if (this == obj) {
283            return true;
284          }
285          if (obj instanceof EquivalentToPredicate) {
286            EquivalentToPredicate<?> that = (EquivalentToPredicate<?>) obj;
287            return equivalence.equals(that.equivalence)
288                && Objects.equal(target, that.target);
289          }
290          return false;
291        }
292    
293        
294        @Override
295        public int hashCode() {
296          return Objects.hashCode(equivalence, target);
297        }
298    
299        
300        @Override
301        public String toString() {
302          return equivalence + ".equivalentTo(" + target + ")";
303        }
304    
305        private static final long serialVersionUID = 0;
306      }
307    
308      /**
309       * Returns an equivalence that delegates to {@link Object#equals} and {@link Object#hashCode}.
310       * {@link Equivalence#equivalent} returns {@code true} if both values are null, or if neither
311       * value is null and {@link Object#equals} returns {@code true}. {@link Equivalence#hash} returns
312       * {@code 0} if passed a null value.
313       *
314       * @since 13.0
315       * @since 8.0 (in Equivalences with null-friendly behavior)
316       * @since 4.0 (in Equivalences)
317       */
318      public static Equivalence<Object> equals() {
319        return Equals.INSTANCE;
320      }
321    
322      /**
323       * Returns an equivalence that uses {@code ==} to compare values and {@link
324       * System#identityHashCode(Object)} to compute the hash code.  {@link Equivalence#equivalent}
325       * returns {@code true} if {@code a == b}, including in the case that a and b are both null.
326       *
327       * @since 13.0
328       * @since 4.0 (in Equivalences)
329       */
330      public static Equivalence<Object> identity() {
331        return Identity.INSTANCE;
332      }
333    
334      static final class Equals extends Equivalence<Object>
335          implements Serializable {
336        
337        static final Equals INSTANCE = new Equals();
338    
339        @Override
340        protected boolean doEquivalent(Object a, Object b) {
341          return a.equals(b);
342        }
343        @Override
344        public int doHash(Object o) {
345          return o.hashCode();
346        }
347    
348        private Object readResolve() {
349          return INSTANCE;
350        } 
351        private static final long serialVersionUID = 1;
352      }
353      
354      static final class Identity extends Equivalence<Object>
355          implements Serializable {
356        
357        static final Identity INSTANCE = new Identity();
358        
359        @Override
360        protected boolean doEquivalent(Object a, Object b) {
361          return false;
362        }
363    
364        @Override
365        protected int doHash(Object o) {
366          return System.identityHashCode(o);
367        }
368     
369        private Object readResolve() {
370          return INSTANCE;
371        }
372        private static final long serialVersionUID = 1;
373      }
374    }