com.google.common.base.Equivalence Maven / Gradle / Ivy
/*
* Copyright (C) 2010 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.common.base;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import com.google.errorprone.annotations.ForOverride;
import java.io.Serializable;
import java.util.function.BiPredicate;
import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* A strategy for determining whether two instances are considered equivalent, and for computing
* hash codes in a manner consistent with that equivalence. Two examples of equivalences are the
* {@linkplain #identity() identity equivalence} and the {@linkplain #equals "equals" equivalence}.
*
* @author Bob Lee
* @author Ben Yu
* @author Gregory Kick
* @since 10.0 (mostly
* source-compatible since 4.0)
*/
@GwtCompatible
@ElementTypesAreNonnullByDefault
/*
* The type parameter is rather than so that we can use T in the
* doEquivalent and doHash methods to indicate that the parameter cannot be null.
*/
public abstract class Equivalence implements BiPredicate<@Nullable T, @Nullable T> {
/** Constructor for use by subclasses. */
protected Equivalence() {}
/**
* Returns {@code true} if the given objects are considered equivalent.
*
* This method describes an equivalence relation on object references, meaning that for
* all references {@code x}, {@code y}, and {@code z} (any of which may be null):
*
*
* - {@code equivalent(x, x)} is true (reflexive property)
*
- {@code equivalent(x, y)} and {@code equivalent(y, x)} each return the same result
* (symmetric property)
*
- If {@code equivalent(x, y)} and {@code equivalent(y, z)} are both true, then {@code
* equivalent(x, z)} is also true (transitive property)
*
*
* Note that all calls to {@code equivalent(x, y)} are expected to return the same result as
* long as neither {@code x} nor {@code y} is modified.
*/
public final boolean equivalent(@CheckForNull T a, @CheckForNull T b) {
if (a == b) {
return true;
}
if (a == null || b == null) {
return false;
}
return doEquivalent(a, b);
}
/**
* @deprecated Provided only to satisfy the {@link BiPredicate} interface; use {@link #equivalent}
* instead.
* @since 21.0
*/
@Deprecated
@Override
public final boolean test(@CheckForNull T t, @CheckForNull T u) {
return equivalent(t, u);
}
/**
* Implemented by the user to determine whether {@code a} and {@code b} are considered equivalent,
* subject to the requirements specified in {@link #equivalent}.
*
*
This method should not be called except by {@link #equivalent}. When {@link #equivalent}
* calls this method, {@code a} and {@code b} are guaranteed to be distinct, non-null instances.
*
* @since 10.0 (previously, subclasses would override equivalent())
*/
@ForOverride
protected abstract boolean doEquivalent(T a, T b);
/**
* Returns a hash code for {@code t}.
*
*
The {@code hash} has the following properties:
*
*
* - It is consistent: for any reference {@code x}, multiple invocations of {@code
* hash(x}} consistently return the same value provided {@code x} remains unchanged
* according to the definition of the equivalence. The hash need not remain consistent from
* one execution of an application to another execution of the same application.
*
- It is distributable across equivalence: for any references {@code x} and {@code
* y}, if {@code equivalent(x, y)}, then {@code hash(x) == hash(y)}. It is not
* necessary that the hash be distributable across inequivalence. If {@code
* equivalence(x, y)} is false, {@code hash(x) == hash(y)} may still be true.
*
- {@code hash(null)} is {@code 0}.
*
*/
public final int hash(@CheckForNull T t) {
if (t == null) {
return 0;
}
return doHash(t);
}
/**
* Implemented by the user to return a hash code for {@code t}, subject to the requirements
* specified in {@link #hash}.
*
* This method should not be called except by {@link #hash}. When {@link #hash} calls this
* method, {@code t} is guaranteed to be non-null.
*
* @since 10.0 (previously, subclasses would override hash())
*/
@ForOverride
protected abstract int doHash(T t);
/**
* Returns a new equivalence relation for {@code F} which evaluates equivalence by first applying
* {@code function} to the argument, then evaluating using {@code this}. That is, for any pair of
* non-null objects {@code x} and {@code y}, {@code equivalence.onResultOf(function).equivalent(a,
* b)} is true if and only if {@code equivalence.equivalent(function.apply(a), function.apply(b))}
* is true.
*
*
For example:
*
*
{@code
* Equivalence SAME_AGE = Equivalence.equals().onResultOf(GET_PERSON_AGE);
* }
*
* {@code function} will never be invoked with a null value.
*
*
Note that {@code function} must be consistent according to {@code this} equivalence
* relation. That is, invoking {@link Function#apply} multiple times for a given value must return
* equivalent results. For example, {@code
* Equivalence.identity().onResultOf(Functions.toStringFunction())} is broken because it's not
* guaranteed that {@link Object#toString}) always returns the same string instance.
*
* @since 10.0
*/
public final Equivalence onResultOf(Function super F, ? extends @Nullable T> function) {
return new FunctionalEquivalence<>(function, this);
}
/**
* Returns a wrapper of {@code reference} that implements {@link Wrapper#equals(Object)
* Object.equals()} such that {@code wrap(a).equals(wrap(b))} if and only if {@code equivalent(a,
* b)}.
*
* @since 10.0
*/
public final Wrapper wrap(@ParametricNullness S reference) {
/*
* I'm pretty sure that this warning "makes sense" but doesn't indicate a real problem.
*
* Why it "makes sense": If we pass a `@Nullable Foo`, then we should also pass an
* `Equivalence super @Nullable Foo>`. And there's no such thing because Equivalence doesn't
* permit nullable type arguments.
*
* Why there's no real problem: Every Equivalence can handle null.
*
* We could work around this by giving Wrapper 2 type parameters. In the terms of this method,
* that would be both the T parameter (from the class) and the S parameter (from this method).
* However, such a change would be source-incompatible. (Plus, there's no reason for the S
* parameter from the user's perspective, so it would be a wart.)
*
* We could probably also work around this by making Wrapper non-final and putting the
* implementation into a subclass with those 2 type parameters. But we like `final`, if only to
* deter users from using mocking frameworks to construct instances. (And could also complicate
* serialization, which is discussed more in the next paragraph.)
*
* We could probably also work around this by having Wrapper accept an instance of a new
* WrapperGuts class, which would then be the class that would declare the 2 type parameters.
* But that would break deserialization of previously serialized Wrapper instances. And while we
* specifically say not to rely on serialization across Guava versions, users sometimes do. So
* we'd rather not break them without a good enough reason.
*
* (We could work around the serialization problem by writing custom serialization code. But
* even that helps only the case of serializing with an old version and deserializing with a
* new, not vice versa -- unless we introduce WrapperGuts and the logic to handle it today, wait
* until "everyone" has picked up a version of Guava with that code, and *then* change to use
* WrapperGuts.)
*
* Anyway, a suppression isn't really a big deal. But I have tried to do some due diligence on
* avoiding it :)
*/
@SuppressWarnings("nullness")
Wrapper w = new Wrapper<>(this, reference);
return w;
}
/**
* Wraps an object so that {@link #equals(Object)} and {@link #hashCode()} delegate to an {@link
* Equivalence}.
*
* For example, given an {@link Equivalence} for {@link String strings} named {@code equiv}
* that tests equivalence using their lengths:
*
*
{@code
* equiv.wrap("a").equals(equiv.wrap("b")) // true
* equiv.wrap("a").equals(equiv.wrap("hello")) // false
* }
*
* Note in particular that an equivalence wrapper is never equal to the object it wraps.
*
*
{@code
* equiv.wrap(obj).equals(obj) // always false
* }
*
* @since 10.0
*/
public static final class Wrapper implements Serializable {
private final Equivalence super T> equivalence;
@ParametricNullness private final T reference;
private Wrapper(Equivalence super T> equivalence, @ParametricNullness T reference) {
this.equivalence = checkNotNull(equivalence);
this.reference = reference;
}
/** Returns the (possibly null) reference wrapped by this instance. */
@ParametricNullness
public T get() {
return reference;
}
/**
* Returns {@code true} if {@link Equivalence#equivalent(Object, Object)} applied to the wrapped
* references is {@code true} and both wrappers use the {@link Object#equals(Object) same}
* equivalence.
*/
@Override
public boolean equals(@CheckForNull Object obj) {
if (obj == this) {
return true;
}
if (obj instanceof Wrapper) {
Wrapper> that = (Wrapper>) obj; // note: not necessarily a Wrapper
if (this.equivalence.equals(that.equivalence)) {
/*
* We'll accept that as sufficient "proof" that either equivalence should be able to
* handle either reference, so it's safe to circumvent compile-time type checking.
*/
@SuppressWarnings("unchecked")
Equivalence