Collections.emptyList() instead of null check?

后端 未结 9 1086
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-04 02:59

If I have a rarely used collection in some class which may be instantiated many times, I may sometimes resort to the following \"idiom\" in order to save unnecessary object crea

相关标签:
9条回答
  • 2021-02-04 03:22

    Here's a variation on using optional as @Stas suggested, but also using the isEmpty immutable collection as originally requested in the question:

    public static List<String> addElement(List<String> list, String toAdd) {
       List<String> newList = Optional.ofNullable(list).orElse(Collections.emptyList());
       newList.add(toAdd);
       return newList;
    }
    

    This approach is also the closest thing I can find to the nice ability in Javascript to use an empty array if the collection is null.

    For example:

    // no need to indent everything inside a null check of myObjects
    for (MyObj myObj : Optional.ofNullable(myObjects).orElse(Collections.emptyList())){
        // do stuff with myObj
    }
    
    0 讨论(0)
  • 2021-02-04 03:27

    If you only use the list for iterations, you could just use: for (Object object : list) which wouldn't do anything for empty lists, i.e. not a single iteration.

    Otherwise just check list.isEmpty().

    0 讨论(0)
  • 2021-02-04 03:29

    There is an emptyIfNull method in package org.apache.commons.collections4;. It returns an empty list if the one provided is null.

    List<Object> list = CollectionUtils.emptyIfNull(list);
    
    0 讨论(0)
提交回复
热议问题