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 java.io.Serializable; 021import javax.annotation.Nullable; 022 023/** 024 * A strategy for determining whether two instances are considered equivalent. Examples of 025 * equivalences are the {@linkplain #identity() identity equivalence} and {@linkplain #equals equals 026 * equivalence}. 027 * 028 * <h3>For Java 8+ users</h3> 029 * 030 * <p>A future version of this class will implement {@code BiPredicate<T, T>}. In the meantime, to 031 * use an equivalence (say, named {@code equivalence}) as a bi-predicate, use the method reference 032 * {@code equivalence::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 /** 043 * Constructor for use by subclasses. 044 */ 045 protected Equivalence() {} 046 047 /** 048 * Returns {@code true} if the given objects are considered equivalent. 049 * 050 * <p>The {@code equivalent} method implements an equivalence relation on object references: 051 * 052 * <ul> 053 * <li>It is <i>reflexive</i>: for any reference {@code x}, including null, {@code 054 * equivalent(x, x)} returns {@code true}. 055 * <li>It is <i>symmetric</i>: for any references {@code x} and {@code y}, {@code 056 * equivalent(x, y) == equivalent(y, x)}. 057 * <li>It is <i>transitive</i>: for any references {@code x}, {@code y}, and {@code z}, if 058 * {@code equivalent(x, y)} returns {@code true} and {@code equivalent(y, z)} returns {@code 059 * true}, then {@code equivalent(x, z)} returns {@code true}. 060 * <li>It is <i>consistent</i>: for any references {@code x} and {@code y}, multiple invocations 061 * of {@code equivalent(x, y)} consistently return {@code true} or consistently return {@code 062 * false} (provided that neither {@code x} nor {@code y} is modified). 063 * </ul> 064 */ 065 public final boolean equivalent(@Nullable T a, @Nullable T b) { 066 if (a == b) { 067 return true; 068 } 069 if (a == null || b == null) { 070 return false; 071 } 072 return doEquivalent(a, b); 073 } 074 075 /** 076 * Returns {@code true} if {@code a} and {@code b} are considered equivalent. 077 * 078 * <p>Called by {@link #equivalent}. {@code a} and {@code b} are not the same object and are not 079 * nulls. 080 * 081 * @since 10.0 (previously, subclasses would override equivalent()) 082 */ 083 protected abstract boolean doEquivalent(T a, T b); 084 085 /** 086 * Returns a hash code for {@code t}. 087 * 088 * <p>The {@code hash} has the following properties: 089 * <ul> 090 * <li>It is <i>consistent</i>: for any reference {@code x}, multiple invocations of 091 * {@code hash(x}} consistently return the same value provided {@code x} remains unchanged 092 * according to the definition of the equivalence. The hash need not remain consistent from 093 * one execution of an application to another execution of the same application. 094 * <li>It is <i>distributable across equivalence</i>: for any references {@code x} and {@code y}, 095 * if {@code equivalent(x, y)}, then {@code hash(x) == hash(y)}. It is <i>not</i> necessary 096 * that the hash be distributable across <i>inequivalence</i>. If {@code equivalence(x, y)} is 097 * false, {@code hash(x) == hash(y)} may still be true. 098 * <li>{@code hash(null)} is {@code 0}. 099 * </ul> 100 */ 101 public final int hash(@Nullable T t) { 102 if (t == null) { 103 return 0; 104 } 105 return doHash(t); 106 } 107 108 /** 109 * Returns a hash code for non-null object {@code t}. 110 * 111 * <p>Called by {@link #hash}. 112 * 113 * @since 10.0 (previously, subclasses would override hash()) 114 */ 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 121 * equivalence.onResultOf(function).equivalent(a, b)} is true if and only if {@code 122 * equivalence.equivalent(function.apply(a), function.apply(b))} is true. 123 * 124 * <p>For example: 125 * 126 * <pre> {@code 127 * Equivalence<Person> SAME_AGE = Equivalence.equals().onResultOf(GET_PERSON_AGE);}</pre> 128 * 129 * <p>{@code function} will never be invoked with a null value. 130 * 131 * <p>Note that {@code function} must be consistent according to {@code this} equivalence 132 * relation. That is, invoking {@link Function#apply} multiple times for a given value must return 133 * equivalent results. For example, 134 * {@code Equivalence.identity().onResultOf(Functions.toStringFunction())} is broken because it's 135 * not guaranteed that {@link Object#toString}) always returns the same string instance. 136 * 137 * @since 10.0 138 */ 139 public final <F> Equivalence<F> onResultOf(Function<F, ? extends T> function) { 140 return new FunctionalEquivalence<F, T>(function, this); 141 } 142 143 /** 144 * Returns a wrapper of {@code reference} that implements {@link Wrapper#equals(Object) 145 * Object.equals()} such that {@code wrap(a).equals(wrap(b))} if and only if 146 * {@code equivalent(a, b)}. 147 * 148 * @since 10.0 149 */ 150 public final <S extends T> Wrapper<S> wrap(@Nullable S reference) { 151 return new Wrapper<S>(this, reference); 152 } 153 154 /** 155 * Wraps an object so that {@link #equals(Object)} and {@link #hashCode()} delegate to an 156 * {@link Equivalence}. 157 * 158 * <p>For example, given an {@link Equivalence} for {@link String strings} named {@code equiv} 159 * that tests equivalence using their lengths: 160 * 161 * <pre> {@code 162 * equiv.wrap("a").equals(equiv.wrap("b")) // true 163 * equiv.wrap("a").equals(equiv.wrap("hello")) // false}</pre> 164 * 165 * <p>Note in particular that an equivalence wrapper is never equal to the object it wraps. 166 * 167 * <pre> {@code 168 * equiv.wrap(obj).equals(obj) // always false}</pre> 169 * 170 * @since 10.0 171 */ 172 public static final class Wrapper<T> implements Serializable { 173 private final Equivalence<? super T> equivalence; 174 @Nullable private final T reference; 175 176 private Wrapper(Equivalence<? super T> equivalence, @Nullable T reference) { 177 this.equivalence = checkNotNull(equivalence); 178 this.reference = reference; 179 } 180 181 /** Returns the (possibly null) reference wrapped by this instance. */ 182 @Nullable 183 public T get() { 184 return reference; 185 } 186 187 /** 188 * Returns {@code true} if {@link Equivalence#equivalent(Object, Object)} applied to the wrapped 189 * references is {@code true} and both wrappers use the {@link Object#equals(Object) same} 190 * equivalence. 191 */ 192 @Override 193 public boolean equals(@Nullable Object obj) { 194 if (obj == this) { 195 return true; 196 } 197 if (obj instanceof Wrapper) { 198 Wrapper<?> that = (Wrapper<?>) obj; // note: not necessarily a Wrapper<T> 199 200 if (this.equivalence.equals(that.equivalence)) { 201 /* 202 * We'll accept that as sufficient "proof" that either equivalence should be able to 203 * handle either reference, so it's safe to circumvent compile-time type checking. 204 */ 205 @SuppressWarnings("unchecked") 206 Equivalence<Object> equivalence = (Equivalence<Object>) this.equivalence; 207 return equivalence.equivalent(this.reference, that.reference); 208 } 209 } 210 return false; 211 } 212 213 /** 214 * Returns the result of {@link Equivalence#hash(Object)} applied to the wrapped reference. 215 */ 216 @Override 217 public int hashCode() { 218 return equivalence.hash(reference); 219 } 220 221 /** 222 * Returns a string representation for this equivalence wrapper. The form of this string 223 * representation is not specified. 224 */ 225 @Override 226 public String toString() { 227 return equivalence + ".wrap(" + reference + ")"; 228 } 229 230 private static final long serialVersionUID = 0; 231 } 232 233 /** 234 * Returns an equivalence over iterables based on the equivalence of their elements. More 235 * specifically, two iterables are considered equivalent if they both contain the same number of 236 * elements, and each pair of corresponding elements is equivalent according to {@code this}. Null 237 * iterables are equivalent to one another. 238 * 239 * <p>Note that this method performs a similar function for equivalences as 240 * {@link com.google.common.collect.Ordering#lexicographical} does for orderings. 241 * 242 * @since 10.0 243 */ 244 @GwtCompatible(serializable = true) 245 public final <S extends T> Equivalence<Iterable<S>> pairwise() { 246 // Ideally, the returned equivalence would support Iterable<? extends T>. However, 247 // the need for this is so rare that it's not worth making callers deal with the ugly wildcard. 248 return new PairwiseEquivalence<S>(this); 249 } 250 251 /** 252 * Returns a predicate that evaluates to true if and only if the input is equivalent to {@code 253 * target} according to this equivalence relation. 254 * 255 * @since 10.0 256 */ 257 public final Predicate<T> equivalentTo(@Nullable T target) { 258 return new EquivalentToPredicate<T>(this, target); 259 } 260 261 private static final class EquivalentToPredicate<T> implements Predicate<T>, Serializable { 262 263 private final Equivalence<T> equivalence; 264 @Nullable private final T target; 265 266 EquivalentToPredicate(Equivalence<T> equivalence, @Nullable T target) { 267 this.equivalence = checkNotNull(equivalence); 268 this.target = target; 269 } 270 271 @Override 272 public boolean apply(@Nullable T input) { 273 return equivalence.equivalent(input, target); 274 } 275 276 @Override 277 public boolean equals(@Nullable Object obj) { 278 if (this == obj) { 279 return true; 280 } 281 if (obj instanceof EquivalentToPredicate) { 282 EquivalentToPredicate<?> that = (EquivalentToPredicate<?>) obj; 283 return equivalence.equals(that.equivalence) && Objects.equal(target, that.target); 284 } 285 return false; 286 } 287 288 @Override 289 public int hashCode() { 290 return Objects.hashCode(equivalence, target); 291 } 292 293 @Override 294 public String toString() { 295 return equivalence + ".equivalentTo(" + target + ")"; 296 } 297 298 private static final long serialVersionUID = 0; 299 } 300 301 /** 302 * Returns an equivalence that delegates to {@link Object#equals} and {@link Object#hashCode}. 303 * {@link Equivalence#equivalent} returns {@code true} if both values are null, or if neither 304 * value is null and {@link Object#equals} returns {@code true}. {@link Equivalence#hash} returns 305 * {@code 0} if passed a null value. 306 * 307 * @since 13.0 308 * @since 8.0 (in Equivalences with null-friendly behavior) 309 * @since 4.0 (in Equivalences) 310 */ 311 public static Equivalence<Object> equals() { 312 return Equals.INSTANCE; 313 } 314 315 /** 316 * Returns an equivalence that uses {@code ==} to compare values and 317 * {@link System#identityHashCode(Object)} to compute the hash code. 318 * {@link Equivalence#equivalent} returns {@code true} if {@code a == b}, including in the case 319 * 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}