Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

guava

I didn't find the identity-equality Predicate I expected to in com.google.common.base.Predicates so I whipped this up. I've found it useful for assertions in unit tests about the precise behavior of collections (e.g., Multiset<T>) Does this already exist? If not, I think it should but maybe there's something I'm 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);
}
like image 710
nezda Avatar asked Oct 11 '22 18:10

nezda


1 Answers

No it doesn't, and it's also in the idea graveyard as something that won't be done (Predicates.sameAs). I imagine it's more or less for the reasons Mark Peters gives.

like image 161
ColinD Avatar answered Oct 14 '22 04:10

ColinD