加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Java是否也对处理空值的相等性进行了通用测试?

发布时间:2020-12-15 00:03:26 所属栏目:Java 来源:网络整理
导读:Java标准库中是否存在具有静态相等函数的任何地方? public static T boolean equals(T a,T b){ if (a == null) return b == null; else if (b == null) return false; else return a.equals(b);} 我刚刚在一个新的项目Util类中实现了这个,无数次.似乎令人难
Java标准库中是否存在具有静态相等函数的任何地方?
public static <T> boolean equals(T a,T b)
{
    if (a == null)
        return b == null;
    else if (b == null)
        return false;
    else
        return a.equals(b);
}

我刚刚在一个新的项目Util类中实现了这个,无数次.似乎令人难以置信的是它不会作为标准库函数发布……

解决方法

在JDK 7中有 Objects#equals().来自Javadoc:

Returns true if the arguments are equal to each other and false
otherwise. Consequently,if both arguments are null,true is returned
and if exactly one argument is null,false is returned. Otherwise,
equality is determined by using the equals method of the first
argument.

除了Apache Commons Lang中已经提到的功能之外,Google Guava中还有一个功能,Objects#equal():

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读