001/* 002 * Copyright (C) 2010 The Guava Authors 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package com.google.common.base; 018 019import static com.google.common.base.Preconditions.checkNotNull; 020 021import com.google.common.annotations.Beta; 022import com.google.common.annotations.GwtCompatible; 023 024import java.io.Serializable; 025 026import javax.annotation.CheckReturnValue; 027import javax.annotation.Nullable; 028 029/** 030 * A strategy for determining whether two instances are considered equivalent. Examples of 031 * equivalences are the {@linkplain #identity() identity equivalence} and {@linkplain #equals equals 032 * equivalence}. 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" 038 * >mostly source-compatible</a> since 4.0) 039 */ 040@CheckReturnValue 041@GwtCompatible 042public abstract class Equivalence<T> { 043 /** 044 * Constructor for use by subclasses. 045 */ 046 protected Equivalence() {} 047 048 /** 049 * Returns {@code true} if the given objects are considered equivalent. 050 * 051 * <p>The {@code equivalent} method implements an equivalence relation on object references: 052 * 053 * <ul> 054 * <li>It is <i>reflexive</i>: for any reference {@code x}, including null, {@code 055 * equivalent(x, x)} returns {@code true}. 056 * <li>It is <i>symmetric</i>: for any references {@code x} and {@code y}, {@code 057 * equivalent(x, y) == equivalent(y, x)}. 058 * <li>It is <i>transitive</i>: for any references {@code x}, {@code y}, and {@code z}, if 059 * {@code equivalent(x, y)} returns {@code true} and {@code equivalent(y, z)} returns {@code 060 * true}, then {@code equivalent(x, z)} returns {@code true}. 061 * <li>It is <i>consistent</i>: for any references {@code x} and {@code y}, multiple invocations 062 * of {@code equivalent(x, y)} consistently return {@code true} or consistently return {@code 063 * false} (provided that neither {@code x} nor {@code y} is modified). 064 * </ul> 065 */ 066 public final boolean equivalent(@Nullable T a, @Nullable T b) { 067 if (a == b) { 068 return true; 069 } 070 if (a == null || b == null) { 071 return false; 072 } 073 return doEquivalent(a, b); 074 } 075 076 /** 077 * Returns {@code true} if {@code a} and {@code b} are considered equivalent. 078 * 079 * <p>Called by {@link #equivalent}. {@code a} and {@code b} are not the same 080 * object and are not nulls. 081 * 082 * @since 10.0 (previously, subclasses would override equivalent()) 083 */ 084 protected abstract boolean doEquivalent(T a, T b); 085 086 /** 087 * Returns a hash code for {@code t}. 088 * 089 * <p>The {@code hash} has the following properties: 090 * <ul> 091 * <li>It is <i>consistent</i>: for any reference {@code x}, multiple invocations of 092 * {@code hash(x}} consistently return the same value provided {@code x} remains unchanged 093 * according to the definition of the equivalence. The hash need not remain consistent from 094 * one execution of an application to another execution of the same application. 095 * <li>It is <i>distributable across equivalence</i>: for any references {@code x} and {@code y}, 096 * if {@code equivalent(x, y)}, then {@code hash(x) == hash(y)}. It is <i>not</i> necessary 097 * that the hash be distributable across <i>inequivalence</i>. If {@code equivalence(x, y)} 098 * is false, {@code hash(x) == hash(y)} may still be true. 099 * <li>{@code hash(null)} is {@code 0}. 100 * </ul> 101 */ 102 public final int hash(@Nullable T t) { 103 if (t == null) { 104 return 0; 105 } 106 return doHash(t); 107 } 108 109 /** 110 * Returns a hash code for non-null object {@code t}. 111 * 112 * <p>Called by {@link #hash}. 113 * 114 * @since 10.0 (previously, subclasses would override hash()) 115 */ 116 protected abstract int doHash(T t); 117 118 /** 119 * Returns a new equivalence relation for {@code F} which evaluates equivalence by first applying 120 * {@code function} to the argument, then evaluating using {@code this}. That is, for any pair of 121 * non-null objects {@code x} and {@code y}, {@code 122 * equivalence.onResultOf(function).equivalent(a, b)} is true if and only if {@code 123 * equivalence.equivalent(function.apply(a), function.apply(b))} is true. 124 * 125 * <p>For example: 126 * 127 * <pre> {@code 128 * Equivalence<Person> SAME_AGE = Equivalence.equals().onResultOf(GET_PERSON_AGE);}</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. 135 * For example, {@code Equivalence.identity().onResultOf(Functions.toStringFunction())} is broken 136 * because it's not guaranteed that {@link Object#toString}) always returns the same string 137 * instance. 138 * 139 * @since 10.0 140 */ 141 public final <F> Equivalence<F> onResultOf(Function<F, ? extends T> function) { 142 return new FunctionalEquivalence<F, T>(function, this); 143 } 144 145 /** 146 * Returns a wrapper of {@code reference} that implements 147 * {@link Wrapper#equals(Object) Object.equals()} such that 148 * {@code wrap(a).equals(wrap(b))} if and only if {@code equivalent(a, b)}. 149 * 150 * @since 10.0 151 */ 152 public final <S extends T> Wrapper<S> wrap(@Nullable S reference) { 153 return new Wrapper<S>(this, reference); 154 } 155 156 /** 157 * Wraps an object so that {@link #equals(Object)} and {@link #hashCode()} delegate to an 158 * {@link Equivalence}. 159 * 160 * <p>For example, given an {@link Equivalence} for {@link String strings} named {@code equiv} 161 * that tests equivalence using their lengths: 162 * 163 * <pre> {@code 164 * equiv.wrap("a").equals(equiv.wrap("b")) // true 165 * equiv.wrap("a").equals(equiv.wrap("hello")) // false}</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}</pre> 171 * 172 * @since 10.0 173 */ 174 public static final class Wrapper<T> implements Serializable { 175 private final Equivalence<? super T> equivalence; 176 @Nullable private final T reference; 177 178 private Wrapper(Equivalence<? super T> equivalence, @Nullable T reference) { 179 this.equivalence = checkNotNull(equivalence); 180 this.reference = reference; 181 } 182 183 /** Returns the (possibly null) reference wrapped by this instance. */ 184 @Nullable 185 public T get() { 186 return reference; 187 } 188 189 /** 190 * Returns {@code true} if {@link Equivalence#equivalent(Object, Object)} applied to the wrapped 191 * references is {@code true} and both wrappers use the {@link Object#equals(Object) same} 192 * equivalence. 193 */ 194 @Override 195 public boolean equals(@Nullable Object obj) { 196 if (obj == this) { 197 return true; 198 } 199 if (obj instanceof Wrapper) { 200 Wrapper<?> that = (Wrapper<?>) obj; // note: not necessarily a Wrapper<T> 201 202 if (this.equivalence.equals(that.equivalence)) { 203 /* 204 * We'll accept that as sufficient "proof" that either equivalence should be able to 205 * handle either reference, so it's safe to circumvent compile-time type checking. 206 */ 207 @SuppressWarnings("unchecked") 208 Equivalence<Object> equivalence = (Equivalence<Object>) this.equivalence; 209 return equivalence.equivalent(this.reference, that.reference); 210 } 211 } 212 return false; 213 } 214 215 /** 216 * Returns the result of {@link Equivalence#hash(Object)} applied to the wrapped reference. 217 */ 218 @Override 219 public int hashCode() { 220 return equivalence.hash(reference); 221 } 222 223 /** 224 * Returns a string representation for this equivalence wrapper. The form of this string 225 * representation is not specified. 226 */ 227 @Override 228 public String toString() { 229 return equivalence + ".wrap(" + reference + ")"; 230 } 231 232 private static final long serialVersionUID = 0; 233 } 234 235 /** 236 * Returns an equivalence over iterables based on the equivalence of their elements. More 237 * specifically, two iterables are considered equivalent if they both contain the same number of 238 * elements, and each pair of corresponding elements is equivalent according to 239 * {@code this}. Null iterables are equivalent to one another. 240 * 241 * <p>Note that this method performs a similar function for equivalences as {@link 242 * com.google.common.collect.Ordering#lexicographical} does for orderings. 243 * 244 * @since 10.0 245 */ 246 @GwtCompatible(serializable = true) 247 public final <S extends T> Equivalence<Iterable<S>> pairwise() { 248 // Ideally, the returned equivalence would support Iterable<? extends T>. However, 249 // the need for this is so rare that it's not worth making callers deal with the ugly wildcard. 250 return new PairwiseEquivalence<S>(this); 251 } 252 253 /** 254 * Returns a predicate that evaluates to true if and only if the input is 255 * equivalent to {@code target} according to this equivalence relation. 256 * 257 * @since 10.0 258 */ 259 @Beta 260 public final Predicate<T> equivalentTo(@Nullable T target) { 261 return new EquivalentToPredicate<T>(this, target); 262 } 263 264 private static final class EquivalentToPredicate<T> implements Predicate<T>, Serializable { 265 266 private final Equivalence<T> equivalence; 267 @Nullable private final T target; 268 269 EquivalentToPredicate(Equivalence<T> equivalence, @Nullable T target) { 270 this.equivalence = checkNotNull(equivalence); 271 this.target = target; 272 } 273 274 @Override 275 public boolean apply(@Nullable T input) { 276 return equivalence.equivalent(input, target); 277 } 278 279 @Override 280 public boolean equals(@Nullable Object obj) { 281 if (this == obj) { 282 return true; 283 } 284 if (obj instanceof EquivalentToPredicate) { 285 EquivalentToPredicate<?> that = (EquivalentToPredicate<?>) obj; 286 return equivalence.equals(that.equivalence) && Objects.equal(target, that.target); 287 } 288 return false; 289 } 290 291 @Override 292 public int hashCode() { 293 return Objects.hashCode(equivalence, target); 294 } 295 296 @Override 297 public String toString() { 298 return equivalence + ".equivalentTo(" + target + ")"; 299 } 300 301 private static final long serialVersionUID = 0; 302 } 303 304 /** 305 * Returns an equivalence that delegates to {@link Object#equals} and {@link Object#hashCode}. 306 * {@link Equivalence#equivalent} returns {@code true} if both values are null, or if neither 307 * value is null and {@link Object#equals} returns {@code true}. {@link Equivalence#hash} returns 308 * {@code 0} if passed a null value. 309 * 310 * @since 13.0 311 * @since 8.0 (in Equivalences with null-friendly behavior) 312 * @since 4.0 (in Equivalences) 313 */ 314 public static Equivalence<Object> equals() { 315 return Equals.INSTANCE; 316 } 317 318 /** 319 * Returns an equivalence that uses {@code ==} to compare values and {@link 320 * System#identityHashCode(Object)} to compute the hash code. {@link Equivalence#equivalent} 321 * returns {@code true} if {@code a == b}, including in the case that a and b are both null. 322 * 323 * @since 13.0 324 * @since 4.0 (in Equivalences) 325 */ 326 public static Equivalence<Object> identity() { 327 return Identity.INSTANCE; 328 } 329 330 static final class Equals extends Equivalence<Object> implements Serializable { 331 332 static final Equals INSTANCE = new Equals(); 333 334 @Override 335 protected boolean doEquivalent(Object a, Object b) { 336 return a.equals(b); 337 } 338 339 @Override 340 protected int doHash(Object o) { 341 return o.hashCode(); 342 } 343 344 private Object readResolve() { 345 return INSTANCE; 346 } 347 348 private static final long serialVersionUID = 1; 349 } 350 351 static final class Identity extends Equivalence<Object> implements Serializable { 352 353 static final Identity INSTANCE = new Identity(); 354 355 @Override 356 protected boolean doEquivalent(Object a, Object b) { 357 return false; 358 } 359 360 @Override 361 protected int doHash(Object o) { 362 return System.identityHashCode(o); 363 } 364 365 private Object readResolve() { 366 return INSTANCE; 367 } 368 369 private static final long serialVersionUID = 1; 370 } 371}