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