remove elements from CopyOnWriteArrayList

前端 未结 9 1953
醉酒成梦
醉酒成梦 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 09:54

    Iterate over the collection choosing all the elements you want to delete and putting those in a temporary collection. After you finish iteration remove all found elements from the original collection using method removeAll.

    Would that work out for you? I mean, not sure if deletion logic is more complicated than that in your algorithm.

    0 讨论(0)
  • 2020-12-29 09:58

    Ususlly you would iterate first gathering elemenet to be deleted in a separate list then delete them outside the for each loop (which is disguised iterator based loop anyway)

    0 讨论(0)
  • 2020-12-29 10:03

    Below works fine with CopyOnWriteArrayList

    for(String key : list) {
        if (<some condition>) {
            list.remove(key);
        }
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-29 10:12

    You could use Queue instead of List.

    private Queue<Something> queue = new ConcurrentLinkedQueue<Something>();
    

    It's thread safe and supports iterator.remove(). Be aware of the thread-safe behavior of Queue iterators, though (check the javadoc).

    0 讨论(0)
  • 2020-12-29 10:12

    If you want to delete all use just clear(). If you want to keep elements put them in a temporary ArrayList and get them back from there.

    List<Object> tKeepThese= new ArrayList<>();
    for(ListIterator<Object> tIter = theCopyOnWriteArrayList; tIter.hasNext();)
    {
        tObject = tIter.next();
        if(condition to keep element)
            tKeepThese.add(tObject);
    }
    theCopyOnWriteArrayList.clear();
    theCopyOnWriteArrayList.addAll(tKeepThese);
    
    0 讨论(0)
提交回复
热议问题