強(qiáng)烈不建議你用 a.equals(b) 判斷對象相等!
一直以為這個方法是java8的,今天才知道是是1.7的時候,然后翻了一下源碼。
這片文章中會總結(jié)一下與a.equals(b)的區(qū)別,然后對源碼做一個小分析。
一,值是null的情況:
1.a.equals(b), a 是null, 拋出NullPointException異常。
2.a.equals(b), a不是null, b是null, 返回false
3.Objects.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
二,值是空字符串的情況:
1.a 和 b 如果都是空值字符串:"", 則 a.equals(b), 返回的值是true, 如果a和b其中有一個不是空值字符串,則返回false;
2.這種情況下 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.說明
首先,進(jìn)行了對象地址的判斷,如果是真,則不再繼續(xù)判斷。
如果不相等,后面的表達(dá)式的意思是,先判斷a不為空,然后根據(jù)上面的知識點(diǎn),就不會再出現(xiàn)空指針。
所以,如果都是null,在第一個判斷上就為true了。如果不為空,地址不同,就重要的是判斷a.equals(b)。
四,“a==b”和”a.equals(b)”有什么區(qū)別?
如果 a 和 b 都是對象,則 a==b 是比較兩個對象的引用,只有當(dāng) a 和 b 指向的是堆中的同一個對象才會返回 true。
而 a.equals(b) 是進(jìn)行邏輯比較,當(dāng)內(nèi)容相同時,返回true,所以通常需要重寫該方法來提供邏輯一致性的比較。