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 org.jspecify.annotations.NonNull; 024import org.jspecify.annotations.Nullable; 025 026/** 027 * A strategy for determining whether two instances are considered equivalent, and for computing 028 * hash codes in a manner consistent with that equivalence. Two examples of equivalences are the 029 * {@linkplain #identity() identity equivalence} and the {@linkplain #equals "equals" equivalence}. 030 * 031 * @author Bob Lee 032 * @author Ben Yu 033 * @author Gregory Kick 034 * @since 10.0 (<a href="https://github.com/google/guava/wiki/Compatibility">mostly 035 * source-compatible</a> since 4.0) 036 */ 037@GwtCompatible 038/* 039 * The type parameter is <T> rather than <T extends @Nullable> so that we can use T in the 040 * doEquivalent and doHash methods to indicate that the parameter cannot be null. 041 */ 042public abstract class Equivalence<T> implements BiPredicate<@Nullable T, @Nullable T> { 043 /** Constructor for use by subclasses. */ 044 protected Equivalence() {} 045 046 /** 047 * Returns {@code true} if the given objects are considered equivalent. 048 * 049 * <p>This method describes an <i>equivalence relation</i> on object references, meaning that for 050 * all references {@code x}, {@code y}, and {@code z} (any of which may be null): 051 * 052 * <ul> 053 * <li>{@code equivalent(x, x)} is true (<i>reflexive</i> property) 054 * <li>{@code equivalent(x, y)} and {@code equivalent(y, x)} each return the same result 055 * (<i>symmetric</i> property) 056 * <li>If {@code equivalent(x, y)} and {@code equivalent(y, z)} are both true, then {@code 057 * equivalent(x, z)} is also true (<i>transitive</i> property) 058 * </ul> 059 * 060 * <p>Note that all calls to {@code equivalent(x, y)} are expected to return the same result as 061 * long as neither {@code x} nor {@code y} is modified. 062 */ 063 public final boolean equivalent(@Nullable T a, @Nullable T b) { 064 if (a == b) { 065 return true; 066 } 067 if (a == null || b == null) { 068 return false; 069 } 070 return doEquivalent(a, b); 071 } 072 073 /** 074 * @deprecated Provided only to satisfy the {@link BiPredicate} interface; use {@link #equivalent} 075 * instead. 076 * @since 21.0 077 */ 078 @Deprecated 079 @Override 080 public final boolean test(@Nullable T t, @Nullable T u) { 081 return equivalent(t, u); 082 } 083 084 /** 085 * Implemented by the user to determine whether {@code a} and {@code b} are considered equivalent, 086 * subject to the requirements specified in {@link #equivalent}. 087 * 088 * <p>This method should not be called except by {@link #equivalent}. When {@link #equivalent} 089 * calls this method, {@code a} and {@code b} are guaranteed to be distinct, non-null instances. 090 * 091 * @since 10.0 (previously, subclasses would override equivalent()) 092 */ 093 @ForOverride 094 protected abstract boolean doEquivalent(T a, T b); 095 096 /** 097 * Returns a hash code for {@code t}. 098 * 099 * <p>The {@code hash} has the following properties: 100 * 101 * <ul> 102 * <li>It is <i>consistent</i>: for any reference {@code x}, multiple invocations of {@code 103 * hash(x}} consistently return the same value provided {@code x} remains unchanged 104 * according to the definition of the equivalence. The hash need not remain consistent from 105 * one execution of an application to another execution of the same application. 106 * <li>It is <i>distributable across equivalence</i>: for any references {@code x} and {@code 107 * y}, if {@code equivalent(x, y)}, then {@code hash(x) == hash(y)}. It is <i>not</i> 108 * necessary that the hash be distributable across <i>inequivalence</i>. If {@code 109 * equivalence(x, y)} is false, {@code hash(x) == hash(y)} may still be true. 110 * <li>{@code hash(null)} is {@code 0}. 111 * </ul> 112 */ 113 public final int hash(@Nullable T t) { 114 if (t == null) { 115 return 0; 116 } 117 return doHash(t); 118 } 119 120 /** 121 * Implemented by the user to return a hash code for {@code t}, subject to the requirements 122 * specified in {@link #hash}. 123 * 124 * <p>This method should not be called except by {@link #hash}. When {@link #hash} calls this 125 * method, {@code t} is guaranteed to be non-null. 126 * 127 * @since 10.0 (previously, subclasses would override hash()) 128 */ 129 @ForOverride 130 protected abstract int doHash(T t); 131 132 /** 133 * Returns a new equivalence relation for {@code F} which evaluates equivalence by first applying 134 * {@code function} to the argument, then evaluating using {@code this}. That is, for any pair of 135 * non-null objects {@code x} and {@code y}, {@code equivalence.onResultOf(function).equivalent(a, 136 * b)} is true if and only if {@code equivalence.equivalent(function.apply(a), function.apply(b))} 137 * is true. 138 * 139 * <p>For example: 140 * 141 * <pre>{@code 142 * Equivalence<Person> SAME_AGE = Equivalence.equals().onResultOf(GET_PERSON_AGE); 143 * }</pre> 144 * 145 * <p>{@code function} will never be invoked with a null value. 146 * 147 * <p>Note that {@code function} must be consistent according to {@code this} equivalence 148 * relation. That is, invoking {@link Function#apply} multiple times for a given value must return 149 * equivalent results. For example, {@code 150 * Equivalence.identity().onResultOf(Functions.toStringFunction())} is broken because it's not 151 * guaranteed that {@link Object#toString}) always returns the same string instance. 152 * 153 * @since 10.0 154 */ 155 public final <F> Equivalence<F> onResultOf(Function<? super F, ? extends @Nullable T> function) { 156 return new FunctionalEquivalence<>(function, this); 157 } 158 159 /** 160 * Returns a wrapper of {@code reference} that implements {@link Wrapper#equals(Object) 161 * Object.equals()} such that {@code wrap(a).equals(wrap(b))} if and only if {@code equivalent(a, 162 * b)}. 163 * 164 * <p>The returned object is serializable if both this {@code Equivalence} and {@code reference} 165 * are serializable (including when {@code reference} is null). 166 * 167 * @since 10.0 168 */ 169 public final <S extends @Nullable T> Wrapper<S> wrap(@ParametricNullness S reference) { 170 return new Wrapper<>(this, reference); 171 } 172 173 /** 174 * Wraps an object so that {@link #equals(Object)} and {@link #hashCode()} delegate to an {@link 175 * Equivalence}. 176 * 177 * <p>For example, given an {@link Equivalence} for {@link String strings} named {@code equiv} 178 * that tests equivalence using their lengths: 179 * 180 * <pre>{@code 181 * equiv.wrap("a").equals(equiv.wrap("b")) // true 182 * equiv.wrap("a").equals(equiv.wrap("hello")) // false 183 * }</pre> 184 * 185 * <p>Note in particular that an equivalence wrapper is never equal to the object it wraps. 186 * 187 * <pre>{@code 188 * equiv.wrap(obj).equals(obj) // always false 189 * }</pre> 190 * 191 * @since 10.0 192 */ 193 public static final class Wrapper<T extends @Nullable Object> implements Serializable { 194 /* 195 * Equivalence's type argument is always non-nullable: Equivalence<Number>, never 196 * Equivalence<@Nullable Number>. That can still produce wrappers of various types -- 197 * Wrapper<Number>, Wrapper<Integer>, Wrapper<@Nullable Integer>, etc. If we used just 198 * Equivalence<? super T> below, no type could satisfy both that bound and T's own 199 * bound. With this type, they have some overlap: in our example, Equivalence<Number> 200 * and Equivalence<Object>. 201 */ 202 private final Equivalence<? super @NonNull T> equivalence; 203 204 @ParametricNullness private final T reference; 205 206 private Wrapper(Equivalence<? super @NonNull T> equivalence, @ParametricNullness T reference) { 207 this.equivalence = checkNotNull(equivalence); 208 this.reference = reference; 209 } 210 211 /** Returns the (possibly null) reference wrapped by this instance. */ 212 @ParametricNullness 213 public T get() { 214 return reference; 215 } 216 217 /** 218 * Returns {@code true} if {@link Equivalence#equivalent(Object, Object)} applied to the wrapped 219 * references is {@code true} and both wrappers use the {@link Object#equals(Object) same} 220 * equivalence. 221 */ 222 @Override 223 public boolean equals(@Nullable Object obj) { 224 if (obj == this) { 225 return true; 226 } 227 if (obj instanceof Wrapper) { 228 Wrapper<?> that = (Wrapper<?>) obj; // note: not necessarily a Wrapper<T> 229 230 if (this.equivalence.equals(that.equivalence)) { 231 /* 232 * We'll accept that as sufficient "proof" that either equivalence should be able to 233 * handle either reference, so it's safe to circumvent compile-time type checking. 234 */ 235 @SuppressWarnings("unchecked") 236 Equivalence<Object> equivalence = (Equivalence<Object>) this.equivalence; 237 return equivalence.equivalent(this.reference, that.reference); 238 } 239 } 240 return false; 241 } 242 243 /** Returns the result of {@link Equivalence#hash(Object)} applied to the wrapped reference. */ 244 @Override 245 public int hashCode() { 246 return equivalence.hash(reference); 247 } 248 249 /** 250 * Returns a string representation for this equivalence wrapper. The form of this string 251 * representation is not specified. 252 */ 253 @Override 254 public String toString() { 255 return equivalence + ".wrap(" + reference + ")"; 256 } 257 258 private static final long serialVersionUID = 0; 259 } 260 261 /** 262 * Returns an equivalence over iterables based on the equivalence of their elements. More 263 * specifically, two iterables are considered equivalent if they both contain the same number of 264 * elements, and each pair of corresponding elements is equivalent according to {@code this}. Null 265 * iterables are equivalent to one another. 266 * 267 * <p>Note that this method performs a similar function for equivalences as {@link 268 * com.google.common.collect.Ordering#lexicographical} does for orderings. 269 * 270 * <p>The returned object is serializable if this object is serializable. 271 * 272 * @since 10.0 273 */ 274 @GwtCompatible(serializable = true) 275 public final <S extends @Nullable T> Equivalence<Iterable<S>> pairwise() { 276 // Ideally, the returned equivalence would support Iterable<? extends T>. However, 277 // the need for this is so rare that it's not worth making callers deal with the ugly wildcard. 278 return new PairwiseEquivalence<>(this); 279 } 280 281 /** 282 * Returns a predicate that evaluates to true if and only if the input is equivalent to {@code 283 * target} according to this equivalence relation. 284 * 285 * @since 10.0 286 */ 287 public final Predicate<@Nullable T> equivalentTo(@Nullable T target) { 288 return new EquivalentToPredicate<>(this, target); 289 } 290 291 private static final class EquivalentToPredicate<T> 292 implements Predicate<@Nullable T>, Serializable { 293 294 private final Equivalence<T> equivalence; 295 private final @Nullable T target; 296 297 EquivalentToPredicate(Equivalence<T> equivalence, @Nullable T target) { 298 this.equivalence = checkNotNull(equivalence); 299 this.target = target; 300 } 301 302 @Override 303 public boolean apply(@Nullable T input) { 304 return equivalence.equivalent(input, target); 305 } 306 307 @Override 308 public boolean equals(@Nullable Object obj) { 309 if (this == obj) { 310 return true; 311 } 312 if (obj instanceof EquivalentToPredicate) { 313 EquivalentToPredicate<?> that = (EquivalentToPredicate<?>) obj; 314 return equivalence.equals(that.equivalence) && Objects.equal(target, that.target); 315 } 316 return false; 317 } 318 319 @Override 320 public int hashCode() { 321 return Objects.hashCode(equivalence, target); 322 } 323 324 @Override 325 public String toString() { 326 return equivalence + ".equivalentTo(" + target + ")"; 327 } 328 329 private static final long serialVersionUID = 0; 330 } 331 332 /** 333 * Returns an equivalence that delegates to {@link Object#equals} and {@link Object#hashCode}. 334 * {@link Equivalence#equivalent} returns {@code true} if both values are null, or if neither 335 * value is null and {@link Object#equals} returns {@code true}. {@link Equivalence#hash} returns 336 * {@code 0} if passed a null value. 337 * 338 * @since 13.0 339 * @since 8.0 (in Equivalences with null-friendly behavior) 340 * @since 4.0 (in Equivalences) 341 */ 342 public static Equivalence<Object> equals() { 343 return Equals.INSTANCE; 344 } 345 346 /** 347 * Returns an equivalence that uses {@code ==} to compare values and {@link 348 * System#identityHashCode(Object)} to compute the hash code. {@link Equivalence#equivalent} 349 * returns {@code true} if {@code a == b}, including in the case that a and b are both null. 350 * 351 * @since 13.0 352 * @since 4.0 (in Equivalences) 353 */ 354 public static Equivalence<Object> identity() { 355 return Identity.INSTANCE; 356 } 357 358 static final class Equals extends Equivalence<Object> implements Serializable { 359 360 static final Equals INSTANCE = new Equals(); 361 362 @Override 363 protected boolean doEquivalent(Object a, Object b) { 364 return a.equals(b); 365 } 366 367 @Override 368 protected int doHash(Object o) { 369 return o.hashCode(); 370 } 371 372 private Object readResolve() { 373 return INSTANCE; 374 } 375 376 private static final long serialVersionUID = 1; 377 } 378 379 static final class Identity extends Equivalence<Object> implements Serializable { 380 381 static final Identity INSTANCE = new Identity(); 382 383 @Override 384 protected boolean doEquivalent(Object a, Object b) { 385 return false; 386 } 387 388 @Override 389 protected int doHash(Object o) { 390 return System.identityHashCode(o); 391 } 392 393 private Object readResolve() { 394 return INSTANCE; 395 } 396 397 private static final long serialVersionUID = 1; 398 } 399}