java.util.Objects.isNull vs object == null

前端 未结 5 1258
盖世英雄少女心
盖世英雄少女心 2020-12-08 03:57

As you know, java.util.Objects is

This class consists of static utility methods for operating on objects.

One of such methods i

5条回答
  •  爱一瞬间的悲伤
    2020-12-08 04:10

    Would there be any reason/circumstance for which I should use object == null over Objects.isNull() in a if statement?

    Yes, one reason is to keep the code simple. Within if statement object == null is clear and well known. It can not lead to any misbehavior if for example there is a typo.

    My understanding is that Objects.isNull() would remove the chance of accidentally assigning a null value to object by omitting the second =.

    If there is an if (object = null) {} with omitted = it will not compile or it will generate warning in case of Boolean object! Actually there is no reason to use Objects.isNull(object) over object == null within if statement. Here are the two variants side by side:

    if (object == null) {
    }
    
    if (Objects.isNull(object)) {
    }
    

    Should Objects.isNull() be confined to Predicates exclusively?

    It could be said yes, it is confined to Predicates exclusively, although there is no technical hurdle to use the Objects.isNull() everywhere.

    From the public static boolean isNull(Object obj) method's javadoc:

    @apiNoteThis method exists to be used as a java.util.function.Predicate, filter(Objects::isNull)

    So if you use the method as not a predicate you are actually using a more complex and cumbersome expression compared to the simple object == null.

    Here is a snippet to compare the benefit of Objects.isNull(object)

    List list = Arrays.asList("a", "b", null, "c", null);
    
    // As ready-made predicate
    long countNullsWithPredicate = list.stream().filter(Objects::isNull).count();
    
    // Lambda
    long countNullsWithLambda = list.stream().filter(object -> object == null).count();
    
    // Reimplement the Objects::isNull predicate
    long countNullsWithAnonymous = list.stream().filter(new Predicate() {
        @Override
        public boolean test(Object obj) {
            return obj == null;
        }
    }).count();
    
        

    提交回复
    热议问题