Collections.emptyList() instead of null check?

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

    in order to save unnecessary object creations

    That's a really bad idea which will litter your code with == null checks and other handling of corner cases (and presumably end up in null pointer exceptions anyway)!

    Now I was wondering if I couldn't eliminate those null checks using Collections.emptyList()

    No, not really. emptyList() returns an empty list. You could do

    if (list.equals(Collections.emptyList()))
    
    
    

    but that will still throw a NullPointerException if list == null, so it's still not what you're after.

    My recommendation: Always initialize the list to new ArrayList, or, if you for instance want to return an empty list from a method, use Collections.emptyList() instead. (This returns the same instance every time, so no unnecessary object creation there either.)

    And then use .isEmpty() to check if a collection is empty or not.

    提交回复
    热议问题