強(qiáng)烈不建議你用 a.equals(b) 判斷對(duì)象相等!
閱讀本文大概需要 2.8 分鐘。
來自:cnblogs.com/juncaoit/p/12422752.html
一、值是null的情況:
a.equals(b), a 是null, 拋出NullPointException異常。a.equals(b), a不是null, b是null, 返回falseObjects.equals(a, b)比較時(shí), 若a 和 b 都是null, 則返回 true, 如果a 和 b 其中一個(gè)是null, 另一個(gè)不是null, 則返回false。注意:不會(huì)拋出空指針異常。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.equals(b), 返回的值是true, 如果a和b其中有一個(gè)不是空值字符串,則返回false;Objects.equals 與情況1 行為一致。"abc".equals("") → 返回 false
"".equals("abc") → 返回 false
"".equals("") → 返回 true
Objects.equals("abc", "") → 返回 false
Objects.equals("","abc") → 返回 false
Objects.equals("","") → 返回 true
三、源碼分析
1.源碼
public final class Objects {
private Objects() {
throw new 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)
*/
public static boolean equals(Object a, Object b) {
return (a == b) || (a != null && a.equals(b));
}
2.說明
四、“a==b”和”a.equals(b)”有什么區(qū)別?
推薦閱讀:
同學(xué),你要的SpringBoot多圖片上傳回顯功能已經(jīng)實(shí)現(xiàn)了,趕緊收藏吃灰~
最近面試BAT,整理一份面試資料《Java面試BATJ通關(guān)手冊(cè)》,覆蓋了Java核心技術(shù)、JVM、Java并發(fā)、SSM、微服務(wù)、數(shù)據(jù)庫、數(shù)據(jù)結(jié)構(gòu)等等。


