Any null safe alternative to ArrayList.addAll?

后端 未结 4 1802
旧时难觅i
旧时难觅i 2021-02-02 09:35

I was refactoring some old code of mine that I\'ve written and I stumbeled on this code:

    List fullImagePool = new ArrayList<>();
           


        
4条回答
  •  天命终不由人
    2021-02-02 09:41

    Just write a small utility method:

    public static  void addAllIfNotNull(List list, Collection c) {
        if (c != null) {
            list.addAll(c);
        }
    }
    

    so that you can write:

    List fullImagePool = new ArrayList<>();
    addAllIfNotNull(fullImagePool, style.getTestMH());
    addAllIfNotNull(fullImagePool, style.getTrousers());
    addAllIfNotNull(fullImagePool, style.getDetailRevers());
    // ...etc
    

提交回复
热议问题