Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright (C) 2010 The Guava Authors
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 
 package com.google.common.base;
 
 import static com.google.common.base.Preconditions.checkNotNull;
 
 
 
A strategy for determining whether two instances are considered equivalent. Examples of equivalences are the identity equivalence and equals equivalence.

Author(s):
Bob Lee
Ben Yu
Gregory Kick
Since:
10.0 (mostly source-compatible since 4.0)
 
 public abstract class Equivalence<T> {
  
Constructor for use by subclasses.
 
   protected Equivalence() {}

  
Returns true if the given objects are considered equivalent.

The equivalent method implements an equivalence relation on object references:

  • It is reflexive: for any reference x, including null, equivalent(x, x) returns true.
  • It is symmetric: for any references x and y, equivalent(x, y) == equivalent(y, x).
  • It is transitive: for any references x, y, and z, if equivalent(x, y) returns true and equivalent(y, z) returns true, then equivalent(x, z) returns true.
  • It is consistent: for any references x and y, multiple invocations of equivalent(x, y) consistently return true or consistently return false (provided that neither x nor y is modified).
 
   public final boolean equivalent(@Nullable T a, @Nullable T b) {
     if (a == b) {
       return true;
     }
     if (a == null || b == null) {
       return false;
     }
     return doEquivalent(ab);
   }

  
Returns true if a and b are considered equivalent.

Called by equivalent(java.lang.Object,java.lang.Object). a and b are not the same object and are not nulls.

Since:
10.0 (previously, subclasses would override equivalent())
 
   protected abstract boolean doEquivalent(T a, T b);

  
Returns a hash code for t.

The hash has the following properties:

  • It is consistent: for any reference x, multiple invocations of hash(x} consistently return the same value provided x remains unchanged according to the definition of the equivalence. The hash need not remain consistent from one execution of an application to another execution of the same application.
  • It is distributable accross equivalence: for any references x and y, if equivalent(x, y), then hash(x) == hash(y). It is not necessary that the hash be distributable accorss inequivalence. If equivalence(x, y) is false, hash(x) == hash(y) may still be true.
  • hash(null) is 0.
 
  public final int hash(@Nullable T t) {
    if (t == null) {
      return 0;
    }
    return doHash(t);
  }

  
Returns a hash code for non-null object t.

Called by hash(java.lang.Object).

Since:
10.0 (previously, subclasses would override hash())
  protected abstract int doHash(T t);

  
Returns a new equivalence relation for F which evaluates equivalence by first applying function to the argument, then evaluating using this. That is, for any pair of non-null objects x and y, equivalence.onResultOf(function).equivalent(a, b) is true if and only if equivalence.equivalent(function.apply(a), function.apply(b)) is true.

For example:

   Equivalence<Person> SAME_AGE = Equivalence.equals().onResultOf(GET_PERSON_AGE);

function will never be invoked with a null value.

Note that function must be consistent according to this equivalence relation. That is, invoking Function.apply(java.lang.Object) multiple times for a given value must return equivalent results. For example, Equivalence.identity().onResultOf(Functions.toStringFunction()) is broken because it's not guaranteed that java.lang.Object.toString()) always returns the same string instance.

Since:
10.0
  public final <F> Equivalence<F> onResultOf(Function<F, ? extends T> function) {
    return new FunctionalEquivalence<F, T>(functionthis);
  }
  
  
Returns a wrapper of reference that implements Object.equals() such that wrap(this, a).equals(wrap(this, b)) if and only if this.equivalent(a, b).

Since:
10.0
  public final <S extends T> Wrapper<S> wrap(@Nullable S reference) {
    return new Wrapper<S>(thisreference);
  }

  
Wraps an object so that equals(java.lang.Object) and hashCode() delegate to an Equivalence.

For example, given an Equivalence for strings named equiv that tests equivalence using their lengths:

   equiv.wrap("a").equals(equiv.wrap("b")) // true
   equiv.wrap("a").equals(equiv.wrap("hello")) // false

Note in particular that an equivalence wrapper is never equal to the object it wraps.

   equiv.wrap(obj).equals(obj) // always false

Since:
10.0
  public static final class Wrapper<T> implements Serializable {
    private final Equivalence<? super T> equivalence;
    @Nullable private final T reference;
    private Wrapper(Equivalence<? super T> equivalence, @Nullable T reference) {
      this. = checkNotNull(equivalence);
      this. = reference;
    }

    
Returns the (possibly null) reference wrapped by this instance.
    @Nullable public T get() {
      return ;
    }

    
Returns true if Equivalence.equivalent(java.lang.Object,java.lang.Object) applied to the wrapped references is true and both wrappers use the same equivalence.
    @Override public boolean equals(@Nullable Object obj) {
      if (obj == this) {
        return true;
      } else if (obj instanceof Wrapper) {
        Wrapper<?> that = (Wrapper<?>) obj;
        /*
         * We cast to Equivalence<Object> here because we can't check the type of the reference held
         * by the other wrapper.  But, by checking that the Equivalences are equal, we know that
         * whatever type it is, it is assignable to the type handled by this wrapper's equivalence.
         */
        @SuppressWarnings("unchecked")
        Equivalence<Objectequivalence = (Equivalence<Object>) this.;
        return equivalence.equals(that.equivalence)
            && equivalence.equivalent(this.that.reference);
      } else {
        return false;
      }
    }

    
Returns the result of Equivalence.hash(java.lang.Object) applied to the wrapped reference.
    @Override public int hashCode() {
      return .hash();
    }

    
Returns a string representation for this equivalence wrapper. The form of this string representation is not specified.
    @Override public String toString() {
      return  + ".wrap(" +  + ")";
    }
    private static final long serialVersionUID = 0;
  }

  
Returns an equivalence over iterables based on the equivalence of their elements. More specifically, two iterables are considered equivalent if they both contain the same number of elements, and each pair of corresponding elements is equivalent according to this. Null iterables are equivalent to one another.

Note that this method performs a similar function for equivalences as com.google.common.collect.Ordering.lexicographical() does for orderings.

Since:
10.0
  @GwtCompatible(serializable = true)
  public final <S extends T> Equivalence<Iterable<S>> pairwise() {
    // Ideally, the returned equivalence would support Iterable<? extends T>. However,
    // the need for this is so rare that it's not worth making callers deal with the ugly wildcard.
    return new PairwiseEquivalence<S>(this);
  }
  
  
Returns a predicate that evaluates to true if and only if the input is equivalent to target according to this equivalence relation.

Since:
10.0
  @Beta
  public final Predicate<T> equivalentTo(@Nullable T target) {
    return new EquivalentToPredicate<T>(thistarget);
  }
  private static final class EquivalentToPredicate<T> implements Predicate<T>, Serializable {
    private final Equivalence<T> equivalence;
    @Nullable private final T target;
    EquivalentToPredicate(Equivalence<T> equivalence, @Nullable T target) {
      this. = checkNotNull(equivalence);
      this. = target;
    }
    @Override public boolean apply(@Nullable T input) {
      return .equivalent(input);
    }
    @Override public boolean equals(@Nullable Object obj) {
      if (this == obj) {
        return true;
      }
      if (obj instanceof EquivalentToPredicate) {
        EquivalentToPredicate<?> that = (EquivalentToPredicate<?>) obj;
        return .equals(that.equivalence)
            && Objects.equal(that.target);
      }
      return false;
    }
    @Override public int hashCode() {
      return Objects.hashCode();
    }
    @Override public String toString() {
      return  + ".equivalentTo(" +  + ")";
    }
    private static final long serialVersionUID = 0;
  }

  
Returns an equivalence that delegates to java.lang.Object.equals(java.lang.Object) and java.lang.Object.hashCode(). equivalent(java.lang.Object,java.lang.Object) returns true if both values are null, or if neither value is null and java.lang.Object.equals(java.lang.Object) returns true. hash(java.lang.Object) returns 0 if passed a null value.

Since:
13.0
8.0 (in Equivalences with null-friendly behavior)
4.0 (in Equivalences)
  public static Equivalence<Objectequals() {
    return .;
  }

  
Returns an equivalence that uses == to compare values and java.lang.System.identityHashCode(java.lang.Object) to compute the hash code. equivalent(java.lang.Object,java.lang.Object) returns true if a == b, including in the case that a and b are both null.

Since:
13.0
4.0 (in Equivalences)
  public static Equivalence<Objectidentity() {
    return .;
  }
  static final class Equals extends Equivalence<Object>
      implements Serializable {
    
    static final Equals INSTANCE = new Equals();
    @Override protected boolean doEquivalent(Object aObject b) {
      return a.equals(b);
    }
    @Override public int doHash(Object o) {
      return o.hashCode();
    }
    private Object readResolve() {
      return ;
    } 
    private static final long serialVersionUID = 1;
  }
  
  static final class Identity extends Equivalence<Object>
      implements Serializable {
    
    static final Identity INSTANCE = new Identity();
    
    @Override protected boolean doEquivalent(Object aObject b) {
      return false;
    }
    @Override protected int doHash(Object o) {
      return System.identityHashCode(o);
    }
 
    private Object readResolve() {
      return ;
    }
    private static final long serialVersionUID = 1;
  }
New to GrepCode? Check out our FAQ X