Collections.emptyList() instead of null check?

后端 未结 9 1082
佛祖请我去吃肉
佛祖请我去吃肉 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:15

    The suggested answers are absolutely correct, just small tip - in Java 8 you can use the new Optional class to handle the case where the list instance is null, in a more functional approach.

    For example, something like this:

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

    Following a tip in the comments, it's better to replace new ArrayList<>() with Collections.emptyList() in order to prevent the creation of a new instance of an empty ArrayList

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

提交回复
热议问题