Does Guava provide Predicates.is (T) (a la Predicates.equalTo (T t)) for equality of identity?

I did not find the equality identifier Predicatethat I expected in com.google.common.base.Predicates, so I hacked it. I found this useful for statements in unit tests about the exact behavior of collections (e.g., Multiset<T>). Does it already exist? If not, I think it should be, but maybe there is something that I am not considering?

/** @see Predicates#is(Object) */
private static class IsPredicate<T> implements Predicate<T>, Serializable {
  private final T target;

  private IsPredicate(T target) {
    this.target = target;
  }
  public boolean apply(T t) {
    return target == t;
  }
  @Override public int hashCode() {
    return target.hashCode();
  }
  @Override public boolean equals(Object obj) {
    if (obj instanceof IsPredicate) {
      IsPredicate<?> that = (IsPredicate<?>) obj;
      return target.equals(that.target);
    }
    return false;
  }
  @Override public String toString() {
    return "Is(" + target + ")";
  }
  private static final long serialVersionUID = 0;
}

/**
 * Returns a predicate that evaluates to {@code true} if the object being
 * tested {@code ==} the given target or both are null.
 */
public static <T> Predicate<T> is(T target) {
  return (target == null)
      ? Predicates.<T>isNull()
      : new IsPredicate<T>(target);
}
+5
source share
1 answer

No, this is not so, and it is also in the cemetery of ideas as something that will not be done ( Predicates.sameAs). I think this is more or less for the reasons that Mark Peters gives.

+4
source

All Articles