一直以為這個方法是java8的,今天才知道是是1.7的時候,然後翻了一下源碼。
這片文章中會總結一下與a.equals(b)的差別,然後對源碼做一個小分析。
一,值是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。注意:不會抛出空指針異常。
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不為空,然後根據上面的知識點,就不會再出現空指針。
是以,如果都是null,在第一個判斷上就為true了。如果不為空,位址不同,就重要的是判斷a.equals(b)。
四,“a==b”和”a.equals(b)”有什麼差別?
如果 a 和 b 都是對象,則 a==b 是比較兩個對象的引用,隻有當 a 和 b 指向的是堆中的同一個對象才會傳回 true。
而 a.equals(b) 是進行邏輯比較,當内容相同時,傳回true,是以通常需要重寫該方法來提供邏輯一緻性的比較。