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?
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;
}
public static <T> Predicate<T> is(T target) {
return (target == null)
? Predicates.<T>isNull()
: new IsPredicate<T>(target);
}
nezda source
share