remove elements from CopyOnWriteArrayList

前端 未结 9 2004
醉酒成梦
醉酒成梦 2020-12-29 09:27

I am getting an exception when I try to remove elements from CopyOnWriteArrayList using an iterator. I have noticed that it is documented

Element-c

9条回答
  •  南笙
    南笙 (楼主)
    2020-12-29 10:06

    Since this is a CopyOnWriteArrayList it is totally safe to remove elements while iterating with forEach. No need for fancy algorithms.

    list.forEach(e -> {
        if (shouldRemove(e))
            list.remove(e);
    });
    

    EDIT: Well of course that works if you want to delete elements by reference, not by position.

提交回复
热议问题