不建议你用去a.equals(b)判断是否相等
一:值是null的情况
a.equals(b)
, a 是null, 抛出NullPointException
异常。a.equals(b)
, a不是null, b是null, 返回falseObjects.equals(a, b)
比较时, 若a 和 b 都是null, 则返回 true, 如果a 和 b 其中一个是null, 另一个不是null, 则返回false。注意:不会抛出空指针异常。
null.equals("abc") → 抛出 NullPointerException 异常
"abc".equals(null) → 返回 false
null.equals(null) → 抛出 NullPointerException 异常
Objects.equals(null, "abc") → 返回 false
Objects.equals("abc",null) → 返回 false
Objects.equals(null, null) → 返回 true
二:值是空字符串的情况
- a 和 b 如果都是空值字符串:"", 则 a.equals(b), 返回的值是true, 如果a和b其中有一个不是空值字符串,则返回false;
- 这种情况下 Objects.equals 与情况1 行为一致。
"abc".equals("") → 返回 false
"".equals("abc") → 返回 false
"".equals("") → 返回 true
Objects.equals("abc", "") → 返回 false
Objects.equals("","abc") → 返回 false
Objects.equals("","") → 返回 true
三:源码分析
1.源码.
publicfinalclassObjects{
privateObjects(){
thrownew AssertionError("No java.util.Objects instances for you!");
}
/**
* Returns {@code true} if the arguments are equal to each other
* and {@code false} otherwise.
* Consequently, if both arguments are {@code null}, {@code true}
* is returned and if exactly one argument is {@code null}, {@code
* false} is returned. Otherwise, equality is determined by using
* the {@link Object#equals equals} method of the first
* argument.
*
* @param a an object
* @param b an object to be compared with {@code a} for equality
* @return {@code true} if the arguments are equal to each other
* and {@code false} otherwise
* @see Object#equals(Object)
*/
publicstaticbooleanequals(Object a, Object b){
return (a == b) || (a != null && a.equals(b));
}
...
}
2.说明
首先,进行了对象地址的判断,如果是真,则不再继续判断。
如果不相等,后面的表达式的意思是,先判断a不为空,然后根据上面的知识点,就不会再出现空指针。
所以,如果都是null,在第一个判断上就为true了。如果不为空,地址不同,就重要的是判断a.equals(b)。
来源:cnblogs.com/juncaoit
PS:如果觉得我的分享不错,欢迎大家随手点赞、在看。
关注公众号:Java后端编程,回复下面关键字
要Java学习完整路线,回复 路线
缺Java入门视频,回复: 视频
要Java面试经验,回复 面试
缺Java项目,回复: 项目
进Java粉丝群: 加群
PS:如果觉得我的分享不错,欢迎大家随手点赞、在看。
请备注:666,不然不通过~
最近好文
关键词
字符串
Objects.equals
源码
a.equals
值是
最新评论
推荐文章
作者最新文章
你可能感兴趣的文章
Copyright Disclaimer: The copyright of contents (including texts, images, videos and audios) posted above belong to the User who shared or the third-party website which the User shared from. If you found your copyright have been infringed, please send a DMCA takedown notice to [email protected]. For more detail of the source, please click on the button "Read Original Post" below. For other communications, please send to [email protected].
版权声明:以上内容为用户推荐收藏至CareerEngine平台,其内容(含文字、图片、视频、音频等)及知识版权均属用户或用户转发自的第三方网站,如涉嫌侵权,请通知[email protected]进行信息删除。如需查看信息来源,请点击“查看原文”。如需洽谈其它事宜,请联系[email protected]。
版权声明:以上内容为用户推荐收藏至CareerEngine平台,其内容(含文字、图片、视频、音频等)及知识版权均属用户或用户转发自的第三方网站,如涉嫌侵权,请通知[email protected]进行信息删除。如需查看信息来源,请点击“查看原文”。如需洽谈其它事宜,请联系[email protected]。