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