是否有 Java 标准的“均为空或相等”的静态方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/184863/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a Java standard "both null or equal" static method?
提问by Chris Conway
To save some typing and clarify my code, is there a standard version of the following method?
为了节省一些输入并澄清我的代码,是否有以下方法的标准版本?
public static boolean bothNullOrEqual(Object x, Object y) {
return ( x == null ? y == null : x.equals(y) );
}
采纳答案by Kdeveloper
With Java 7 you can now directly do a null safe equals:
使用 Java 7,您现在可以直接执行 null 安全等于:
(The Jakarta Commons library ObjectUtils.equals() has become obsolete with Java 7)
(Jakarta Commons 库 ObjectUtils.equals() 在 Java 7 中已经过时了)
回答by Matt
if by some chance you are have access to the Jakarta Commons library there is ObjectUtils.equals()and lots of other useful functions.
如果您有机会访问 Jakarta Commons 库,则有ObjectUtils.equals()和许多其他有用的函数。
EDIT: misread the question initially
编辑:最初误读了这个问题
回答by Sam Berry
If you are using <1.7 but have Guava available: Objects.equal(x, y)
如果您使用的是 <1.7 但有 Guava 可用: Objects.equal(x, y)