是否有一个 Java 标准的“同时为空或相等”的静态方法?

为了保存一些输入并澄清我的代码,是否有以下方法的标准版本?

public static boolean bothNullOrEqual(Object x, Object y) {
return ( x == null ? y == null : x.equals(y) );
}
34953 次浏览

if by some chance you are have access to the Jakarta Commons library there is ObjectUtils.equals() and lots of other useful functions.

EDIT: misread the question initially

With Java 7 you can now directly do a null safe equals:

Objects.equals(x, y)

(The Jakarta Commons library ObjectUtils.equals() has become obsolete with Java 7)

If you are using <1.7 but have Guava available: Objects.equal(x, y)