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    @Beta
040    @GwtCompatible
041    public abstract class Equivalence<T> {
042      /**
043       * Constructor for use by subclasses.
044       */
045      protected Equivalence() {}
046    
047      /**
048       * Returns {@code true} if the given objects are considered equivalent.
049       *
050       * <p>The {@code equivalent} method implements an equivalence relation on object references:
051       *
052       * <ul>
053       * <li>It is <i>reflexive</i>: for any reference {@code x}, including null, {@code
054       *     equivalent(x, x)} returns {@code true}.
055       * <li>It is <i>symmetric</i>: for any references {@code x} and {@code y}, {@code
056       *     equivalent(x, y) == equivalent(y, x)}.
057       * <li>It is <i>transitive</i>: for any references {@code x}, {@code y}, and {@code z}, if
058       *     {@code equivalent(x, y)} returns {@code true} and {@code equivalent(y, z)} returns {@code
059       *     true}, then {@code equivalent(x, z)} returns {@code true}.
060       * <li>It is <i>consistent</i>: for any references {@code x} and {@code y}, multiple invocations
061       *     of {@code equivalent(x, y)} consistently return {@code true} or consistently return {@code
062       *     false} (provided that neither {@code x} nor {@code y} is modified).
063       * </ul>
064       */
065      public final boolean equivalent(@Nullable T a, @Nullable T b) {
066        if (a == b) {
067          return true;
068        }
069        if (a == null || b == null) {
070          return false;
071        }
072        return doEquivalent(a, b);
073      }
074    
075      /**
076       * Returns {@code true} if {@code a} and {@code b} are considered equivalent.
077       *
078       * <p>Called by {@link #equivalent}. {@code a} and {@code b} are not the same
079       * object and are not nulls.
080       *
081       * @since 10.0 (previously, subclasses would override equivalent())
082       */
083      protected abstract boolean doEquivalent(T a, T b);
084    
085      /**
086       * Returns a hash code for {@code t}.
087       *
088       * <p>The {@code hash} has the following properties:
089       * <ul>
090       * <li>It is <i>consistent</i>: for any reference {@code x}, multiple invocations of
091       *     {@code hash(x}} consistently return the same value provided {@code x} remains unchanged
092       *     according to the definition of the equivalence. The hash need not remain consistent from
093       *     one execution of an application to another execution of the same application.
094       * <li>It is <i>distributable accross equivalence</i>: for any references {@code x} and {@code y},
095       *     if {@code equivalent(x, y)}, then {@code hash(x) == hash(y)}. It is <i>not</i> necessary
096       *     that the hash be distributable accorss <i>inequivalence</i>. If {@code equivalence(x, y)}
097       *     is false, {@code hash(x) == hash(y)} may still be true.
098       * <li>{@code hash(null)} is {@code 0}.
099       * </ul>
100       */
101      public final int hash(@Nullable T t) {
102        if (t == null) {
103          return 0;
104        }
105        return doHash(t);
106      }
107    
108      /**
109       * Returns a hash code for non-null object {@code t}.
110       *
111       * <p>Called by {@link #hash}.
112       *
113       * @since 10.0 (previously, subclasses would override hash())
114       */
115      protected abstract int doHash(T t);
116    
117      /**
118       * Returns a new equivalence relation for {@code F} which evaluates equivalence by first applying
119       * {@code function} to the argument, then evaluating using {@code this}. That is, for any pair of
120       * non-null objects {@code x} and {@code y}, {@code
121       * equivalence.onResultOf(function).equivalent(a, b)} is true if and only if {@code
122       * equivalence.equivalent(function.apply(a), function.apply(b))} is true.
123       *
124       * <p>For example: <pre>   {@code
125       *
126       *    Equivalence<Person> SAME_AGE = Equivalences.equals().onResultOf(GET_PERSON_AGE);
127       * }</pre>
128       * 
129       * <p>{@code function} will never be invoked with a null value.
130       * 
131       * <p>Note that {@code function} must be consistent according to {@code this} equivalence
132       * relation. That is, invoking {@link Function#apply} multiple times for a given value must return
133       * equivalent results.
134       * For example, {@code Equivalences.identity().onResultOf(Functions.toStringFunction())} is broken
135       * because it's not guaranteed that {@link Object#toString}) always returns the same string
136       * instance.
137       * 
138       * @since 10.0
139       */
140      public final <F> Equivalence<F> onResultOf(Function<F, ? extends T> function) {
141        return new FunctionalEquivalence<F, T>(function, this);
142      }
143      
144      /**
145       * Returns a wrapper of {@code reference} that implements
146       * {@link Wrapper#equals(Object) Object.equals()} such that
147       * {@code wrap(this, a).equals(wrap(this, b))} if and only if {@code this.equivalent(a, b)}.
148       * 
149       * @since 10.0
150       */
151      public final <S extends T> Wrapper<S> wrap(@Nullable S reference) {
152        return new Wrapper<S>(this, reference);
153      }
154    
155      /**
156       * Wraps an object so that {@link #equals(Object)} and {@link #hashCode()} delegate to an
157       * {@link Equivalence}.
158       *
159       * <p>For example, given an {@link Equivalence} for {@link String strings} named {@code equiv}
160       * that tests equivalence using their lengths:
161       *
162       * <pre>   {@code
163       *   equiv.wrap("a").equals(equiv.wrap("b")) // true
164       *   equiv.wrap("a").equals(equiv.wrap("hello")) // false
165       * }</pre>
166       *
167       * <p>Note in particular that an equivalence wrapper is never equal to the object it wraps.
168       *
169       * <pre>   {@code
170       *   equiv.wrap(obj).equals(obj) // always false
171       * }</pre>
172       *
173       * @since 10.0
174       */
175      @Beta
176      public static final class Wrapper<T> implements Serializable {
177        private final Equivalence<? super T> equivalence;
178        @Nullable private final T reference;
179    
180        private Wrapper(Equivalence<? super T> equivalence, @Nullable T reference) {
181          this.equivalence = checkNotNull(equivalence);
182          this.reference = reference;
183        }
184    
185        /** Returns the (possibly null) reference wrapped by this instance. */
186        @Nullable public T get() {
187          return reference;
188        }
189    
190        /**
191         * Returns {@code true} if {@link Equivalence#equivalent(Object, Object)} applied to the wrapped
192         * references is {@code true} and both wrappers use the {@link Object#equals(Object) same}
193         * equivalence.
194         */
195        @Override 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        @Override public int hashCode() {
218          return equivalence.hash(reference);
219        }
220    
221        /**
222         * Returns a string representation for this equivalence wrapper. The form of this string
223         * representation is not specified.
224         */
225        @Override public String toString() {
226          return equivalence + ".wrap(" + reference + ")";
227        }
228    
229        private static final long serialVersionUID = 0;
230      }
231    
232      /**
233       * Returns an equivalence over iterables based on the equivalence of their elements.  More
234       * specifically, two iterables are considered equivalent if they both contain the same number of
235       * elements, and each pair of corresponding elements is equivalent according to
236       * {@code this}.  Null iterables are equivalent to one another.
237       * 
238       * <p>Note that this method performs a similar function for equivalences as {@link
239       * com.google.common.collect.Ordering#lexicographical} does for orderings.
240       *
241       * @since 10.0
242       */
243      @GwtCompatible(serializable = true)
244      public final <S extends T> Equivalence<Iterable<S>> pairwise() {
245        // Ideally, the returned equivalence would support Iterable<? extends T>. However,
246        // the need for this is so rare that it's not worth making callers deal with the ugly wildcard.
247        return new PairwiseEquivalence<S>(this);
248      }
249      
250      /**
251       * Returns a predicate that evaluates to true if and only if the input is
252       * equivalent to {@code target} according to this equivalence relation.
253       * 
254       * @since 10.0
255       */
256      public final Predicate<T> equivalentTo(@Nullable T target) {
257        return new EquivalentToPredicate<T>(this, target);
258      }
259    
260      private static final class EquivalentToPredicate<T> implements Predicate<T>, Serializable {
261    
262        private final Equivalence<T> equivalence;
263        @Nullable private final T target;
264    
265        EquivalentToPredicate(Equivalence<T> equivalence, @Nullable T target) {
266          this.equivalence = checkNotNull(equivalence);
267          this.target = target;
268        }
269    
270        @Override public boolean apply(@Nullable T input) {
271          return equivalence.equivalent(input, target);
272        }
273    
274        @Override public boolean equals(@Nullable Object obj) {
275          if (this == obj) {
276            return true;
277          }
278          if (obj instanceof EquivalentToPredicate) {
279            EquivalentToPredicate<?> that = (EquivalentToPredicate<?>) obj;
280            return equivalence.equals(that.equivalence)
281                && Objects.equal(target, that.target);
282          }
283          return false;
284        }
285    
286        @Override public int hashCode() {
287          return Objects.hashCode(equivalence, target);
288        }
289    
290        @Override public String toString() {
291          return equivalence + ".equivalentTo(" + target + ")";
292        }
293    
294        private static final long serialVersionUID = 0;
295      }
296    }