有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

ListIterator和并发修改异常的java问题

我有两个ArrayList,每个都包含一定大小的块:blockList,橡皮擦列表。块是具有两个字段的对象:开始和结束。我需要从另一组块中减去一组块

我必须遍历橡皮擦列表并从区块列表中“擦除”它们重叠的块。因此,我的代码如下所示:

 void eraseBlocks (Arrylist<Blocks> blockList, ArrayList<Blocks> eraserList) {
    ListIterator<Blocks> it = blockList.listIterator();

    for (Blocks eraser: eraserList) {
        while (it.hasNext()) {
            Blocks block= it.next();
            if ((eraser.start <= block.start) && (eraser.end >= block.end))
                 blockList.remove(block);
            else if ((eraser.start <= block.start) && (eraser.end < block.end)){
                 block.set(start, eraser.end);
            else if () {
                        ...
                 //more code for where the eraser partially erases the beginning, end, or splits the block
                 //if statements call the .add(), .set(), and remove() methods on the blockList.
                        ...
                  }
            }
        }

我不明白为什么会出现并发修改异常。我从不修改橡皮擦列表

我试图修改在“block block=it.next();”中指定的块对象陈述我还通过删除或向列表中添加块来修改区块列表。我认为ListIterator的全部意义在于它允许您修改、添加或减去正在浏览的列表

故障跟踪指向块橡皮擦=它。next();作为画线的例外,但我不知道这告诉了我什么

谁能帮我找出我做错了什么

谢谢


共 (3) 个答案

  1. # 1 楼答案

    您需要在Iterator上调用remove(),而不是在List上调用

    从javadoc:

    If a single thread issues a sequence of method invocations that violates the contract of an object, the object may throw this exception. For example, if a thread modifies a collection directly while it is iterating over the collection with a fail-fast iterator, the iterator will thow this exception.

  2. # 2 楼答案

    替换

    blockList.remove(block);
    

    it.remove();
    

    如果你以另一种方式移除一个元素,你可以得到一个CME

  3. # 3 楼答案

    是的,ListIterator的设计允许修改列表。但是您没有使用ListIterator的remove()方法,而是直接操作底层列表本身