AdSense

網頁

2020/5/25

Java Objects.isNull() 幹嘛用的

昨天前同事問我Java 8多了Objects.isNull()方法可判斷一個物件是否為null,但這和obj == null判斷有什麼差別?

Object obj = null;
System.out.println(Objects.isNull(obj)); // true
System.out.println(obj == null); // true

從下面Objects.isNull()的原始碼來看好像沒什麼區別。

public final class Objects {
    ...
    /**
     * Returns {@code true} if the provided reference is {@code null} otherwise
     * returns {@code false}.
     *
     * @apiNote This method exists to be used as a
     * {@link java.util.function.Predicate}, {@code filter(Objects::isNull)}
     *
     * @param obj a reference to be checked against {@code null}
     * @return {@code true} if the provided reference is {@code null} otherwise
     * {@code false}
     *
     * @see java.util.function.Predicate
     * @since 1.8
     */
    public static boolean isNull(Object obj) {
        return obj == null;
    }
    ...
}

其實兩者實際上的作用一樣,只是Objects.isNull()在Java 8的lambda表示式可簡寫為method reference語法Objects::isNull,在語義上比較好讀易懂。

list.stream()
        .filter(Objects::isNull) // method reference
        .map(...)

list.stream()
        .filter(e -> e == null)
        .map(...)

沒有留言:

AdSense