Collections.emptyList() instead of null check?

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

    emptyList() doesn't allocate an object each time.

    I would create less of the object which contains the List so you can create the list every time.

    What you can do is

    private List list = Collections.emptyList();
    
    private List listForWrite() {
        return list.isEmpty() ? list = new ArrayList() : list;
    }
    
    
    void add(Object object) {
        listForWrite().add(object);
    }
    
    
    // avoid creating an Iterator every time.
    for (int i = 0, size = list.size(); i < size; i++) {
         ;
    }
    
        

    提交回复
    热议问题