Coverage Summary for Class: Equivalence (com.google.common.base)

Class Method, % Line, %
Equivalence 40% (4/10) 56.2% (9/16)
Equivalence$Equals 80% (4/5) 80% (4/5)
Equivalence$EquivalentToPredicate 0% (0/5) 0% (0/12)
Equivalence$Identity 0% (0/5) 0% (0/5)
Equivalence$Wrapper 0% (0/6) 0% (0/15)
Total 25.8% (8/31) 24.5% (13/53)


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