001/* 002 * Copyright (C) 2010 The Guava Authors 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 005 * in compliance with the License. You may obtain a copy of the License at 006 * 007 * http://www.apache.org/licenses/LICENSE-2.0 008 * 009 * Unless required by applicable law or agreed to in writing, software distributed under the License 010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 011 * or implied. See the License for the specific language governing permissions and limitations under 012 * the License. 013 */ 014 015package com.google.common.base; 016 017import static com.google.common.base.Preconditions.checkNotNull; 018 019import com.google.common.annotations.GwtCompatible; 020import com.google.errorprone.annotations.ForOverride; 021import java.io.Serializable; 022import java.util.function.BiPredicate; 023import javax.annotation.CheckForNull; 024import org.checkerframework.checker.nullness.qual.NonNull; 025import org.checkerframework.checker.nullness.qual.Nullable; 026 027/** 028 * A strategy for determining whether two instances are considered equivalent, and for computing 029 * hash codes in a manner consistent with that equivalence. Two examples of equivalences are the 030 * {@linkplain #identity() identity equivalence} and the {@linkplain #equals "equals" equivalence}. 031 * 032 * @author Bob Lee 033 * @author Ben Yu 034 * @author Gregory Kick 035 * @since 10.0 (<a href="https://github.com/google/guava/wiki/Compatibility">mostly 036 * source-compatible</a> since 4.0) 037 */ 038@GwtCompatible 039/* 040 * The type parameter is <T> rather than <T extends @Nullable> so that we can use T in the 041 * doEquivalent and doHash methods to indicate that the parameter cannot be null. 042 */ 043public abstract class Equivalence<T> implements BiPredicate<@Nullable T, @Nullable T> { 044 /** Constructor for use by subclasses. */ 045 protected Equivalence() {} 046 047 /** 048 * Returns {@code true} if the given objects are considered equivalent. 049 * 050 * <p>This method describes an <i>equivalence relation</i> on object references, meaning that for 051 * all references {@code x}, {@code y}, and {@code z} (any of which may be null): 052 * 053 * <ul> 054 * <li>{@code equivalent(x, x)} is true (<i>reflexive</i> property) 055 * <li>{@code equivalent(x, y)} and {@code equivalent(y, x)} each return the same result 056 * (<i>symmetric</i> property) 057 * <li>If {@code equivalent(x, y)} and {@code equivalent(y, z)} are both true, then {@code 058 * equivalent(x, z)} is also true (<i>transitive</i> property) 059 * </ul> 060 * 061 * <p>Note that all calls to {@code equivalent(x, y)} are expected to return the same result as 062 * long as neither {@code x} nor {@code y} is modified. 063 */ 064 public final boolean equivalent(@CheckForNull T a, @CheckForNull 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 * @deprecated Provided only to satisfy the {@link BiPredicate} interface; use {@link #equivalent} 076 * instead. 077 * @since 21.0 078 */ 079 @Deprecated 080 @Override 081 public final boolean test(@CheckForNull T t, @CheckForNull T u) { 082 return equivalent(t, u); 083 } 084 085 /** 086 * Implemented by the user to determine whether {@code a} and {@code b} are considered equivalent, 087 * subject to the requirements specified in {@link #equivalent}. 088 * 089 * <p>This method should not be called except by {@link #equivalent}. When {@link #equivalent} 090 * calls this method, {@code a} and {@code b} are guaranteed to be distinct, non-null instances. 091 * 092 * @since 10.0 (previously, subclasses would override equivalent()) 093 */ 094 @ForOverride 095 protected abstract boolean doEquivalent(T a, T b); 096 097 /** 098 * Returns a hash code for {@code t}. 099 * 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 * <p>The returned object is serializable if both this {@code Equivalence} and {@code reference} 166 * are serializable (including when {@code reference} is null). 167 * 168 * @since 10.0 169 */ 170 public final <S extends @Nullable T> Wrapper<S> wrap(@ParametricNullness S reference) { 171 return new Wrapper<>(this, reference); 172 } 173 174 /** 175 * Wraps an object so that {@link #equals(Object)} and {@link #hashCode()} delegate to an {@link 176 * Equivalence}. 177 * 178 * <p>For example, given an {@link Equivalence} for {@link String strings} named {@code equiv} 179 * that tests equivalence using their lengths: 180 * 181 * <pre>{@code 182 * equiv.wrap("a").equals(equiv.wrap("b")) // true 183 * equiv.wrap("a").equals(equiv.wrap("hello")) // false 184 * }</pre> 185 * 186 * <p>Note in particular that an equivalence wrapper is never equal to the object it wraps. 187 * 188 * <pre>{@code 189 * equiv.wrap(obj).equals(obj) // always false 190 * }</pre> 191 * 192 * @since 10.0 193 */ 194 public static final class Wrapper<T extends @Nullable Object> implements Serializable { 195 /* 196 * Equivalence's type argument is always non-nullable: Equivalence<Number>, never 197 * Equivalence<@Nullable Number>. That can still produce wrappers of various types -- 198 * Wrapper<Number>, Wrapper<Integer>, Wrapper<@Nullable Integer>, etc. If we used just 199 * Equivalence<? super T> below, no type could satisfy both that bound and T's own 200 * bound. With this type, they have some overlap: in our example, Equivalence<Number> 201 * and Equivalence<Object>. 202 */ 203 private final Equivalence<? super @NonNull T> equivalence; 204 205 @ParametricNullness private final T reference; 206 207 private Wrapper(Equivalence<? super @NonNull T> equivalence, @ParametricNullness T reference) { 208 this.equivalence = checkNotNull(equivalence); 209 this.reference = reference; 210 } 211 212 /** Returns the (possibly null) reference wrapped by this instance. */ 213 @ParametricNullness 214 public T get() { 215 return reference; 216 } 217 218 /** 219 * Returns {@code true} if {@link Equivalence#equivalent(Object, Object)} applied to the wrapped 220 * references is {@code true} and both wrappers use the {@link Object#equals(Object) same} 221 * equivalence. 222 */ 223 @Override 224 public boolean equals(@CheckForNull Object obj) { 225 if (obj == this) { 226 return true; 227 } 228 if (obj instanceof Wrapper) { 229 Wrapper<?> that = (Wrapper<?>) obj; // note: not necessarily a Wrapper<T> 230 231 if (this.equivalence.equals(that.equivalence)) { 232 /* 233 * We'll accept that as sufficient "proof" that either equivalence should be able to 234 * handle either reference, so it's safe to circumvent compile-time type checking. 235 */ 236 @SuppressWarnings("unchecked") 237 Equivalence<Object> equivalence = (Equivalence<Object>) this.equivalence; 238 return equivalence.equivalent(this.reference, that.reference); 239 } 240 } 241 return false; 242 } 243 244 /** Returns the result of {@link Equivalence#hash(Object)} applied to the wrapped reference. */ 245 @Override 246 public int hashCode() { 247 return equivalence.hash(reference); 248 } 249 250 /** 251 * Returns a string representation for this equivalence wrapper. The form of this string 252 * representation is not specified. 253 */ 254 @Override 255 public String toString() { 256 return equivalence + ".wrap(" + reference + ")"; 257 } 258 259 private static final long serialVersionUID = 0; 260 } 261 262 /** 263 * Returns an equivalence over iterables based on the equivalence of their elements. More 264 * specifically, two iterables are considered equivalent if they both contain the same number of 265 * elements, and each pair of corresponding elements is equivalent according to {@code this}. Null 266 * iterables are equivalent to one another. 267 * 268 * <p>Note that this method performs a similar function for equivalences as {@link 269 * com.google.common.collect.Ordering#lexicographical} does for orderings. 270 * 271 * <p>The returned object is serializable if this object is serializable. 272 * 273 * @since 10.0 274 */ 275 @GwtCompatible(serializable = true) 276 public final <S extends @Nullable T> Equivalence<Iterable<S>> pairwise() { 277 // Ideally, the returned equivalence would support Iterable<? extends T>. However, 278 // the need for this is so rare that it's not worth making callers deal with the ugly wildcard. 279 return new PairwiseEquivalence<>(this); 280 } 281 282 /** 283 * Returns a predicate that evaluates to true if and only if the input is equivalent to {@code 284 * target} according to this equivalence relation. 285 * 286 * @since 10.0 287 */ 288 public final Predicate<@Nullable T> equivalentTo(@CheckForNull T target) { 289 return new EquivalentToPredicate<>(this, target); 290 } 291 292 private static final class EquivalentToPredicate<T> 293 implements Predicate<@Nullable T>, Serializable { 294 295 private final Equivalence<T> equivalence; 296 @CheckForNull private final T target; 297 298 EquivalentToPredicate(Equivalence<T> equivalence, @CheckForNull T target) { 299 this.equivalence = checkNotNull(equivalence); 300 this.target = target; 301 } 302 303 @Override 304 public boolean apply(@CheckForNull T input) { 305 return equivalence.equivalent(input, target); 306 } 307 308 @Override 309 public boolean equals(@CheckForNull Object obj) { 310 if (this == obj) { 311 return true; 312 } 313 if (obj instanceof EquivalentToPredicate) { 314 EquivalentToPredicate<?> that = (EquivalentToPredicate<?>) obj; 315 return equivalence.equals(that.equivalence) && Objects.equal(target, that.target); 316 } 317 return false; 318 } 319 320 @Override 321 public int hashCode() { 322 return Objects.hashCode(equivalence, target); 323 } 324 325 @Override 326 public String toString() { 327 return equivalence + ".equivalentTo(" + target + ")"; 328 } 329 330 private static final long serialVersionUID = 0; 331 } 332 333 /** 334 * Returns an equivalence that delegates to {@link Object#equals} and {@link Object#hashCode}. 335 * {@link Equivalence#equivalent} returns {@code true} if both values are null, or if neither 336 * value is null and {@link Object#equals} returns {@code true}. {@link Equivalence#hash} returns 337 * {@code 0} if passed a null value. 338 * 339 * @since 13.0 340 * @since 8.0 (in Equivalences with null-friendly behavior) 341 * @since 4.0 (in Equivalences) 342 */ 343 public static Equivalence<Object> equals() { 344 return Equals.INSTANCE; 345 } 346 347 /** 348 * Returns an equivalence that uses {@code ==} to compare values and {@link 349 * System#identityHashCode(Object)} to compute the hash code. {@link Equivalence#equivalent} 350 * returns {@code true} if {@code a == b}, including in the case that a and b are both null. 351 * 352 * @since 13.0 353 * @since 4.0 (in Equivalences) 354 */ 355 public static Equivalence<Object> identity() { 356 return Identity.INSTANCE; 357 } 358 359 static final class Equals extends Equivalence<Object> implements Serializable { 360 361 static final Equals INSTANCE = new Equals(); 362 363 @Override 364 protected boolean doEquivalent(Object a, Object b) { 365 return a.equals(b); 366 } 367 368 @Override 369 protected int doHash(Object o) { 370 return o.hashCode(); 371 } 372 373 private Object readResolve() { 374 return INSTANCE; 375 } 376 377 private static final long serialVersionUID = 1; 378 } 379 380 static final class Identity extends Equivalence<Object> implements Serializable { 381 382 static final Identity INSTANCE = new Identity(); 383 384 @Override 385 protected boolean doEquivalent(Object a, Object b) { 386 return false; 387 } 388 389 @Override 390 protected int doHash(Object o) { 391 return System.identityHashCode(o); 392 } 393 394 private Object readResolve() { 395 return INSTANCE; 396 } 397 398 private static final long serialVersionUID = 1; 399 } 400}