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