【问题标题】:Why am I getting java.util.ConcurrentModificationException using Stack in Java?为什么我在 Java 中使用 Stack 得到 java.util.ConcurrentModificationException?
【发布时间】:2013-11-26 05:02:41
【问题描述】:

尽管使用了带有堆栈的迭代器,但我遇到了并发修改异常

package samplecodes;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;

public class ReOrderStack {






    public static Stack<Integer> reorder(Stack<Integer> s )
    {
        Queue <Integer> q= new LinkedList<Integer>();

        if(s==null|| s.isEmpty())
            return s;
        // Use an iterator to prevent concurrent modification exception!

        Iterator<Integer> it = s.iterator();
        while(it.hasNext())
        {
            Integer val= it.next();// concurrent modification exception!
            if(val>=0)
            {
                s.remove(val);
                q.add(val);
            }
        }

    //we've inspected the stack

    //add back from the queue to stack
    while(!q.isEmpty())
    {
        Integer val=q.remove();

        s.push(val);
    }
        return s;

    }
}

有什么想法吗?

【问题讨论】:

  • 您必须通过迭代器进行删除。

标签: java collections iterator stack


【解决方案1】:

Stack.remove 不安全。它发生在ConcurrentModificationExceptionIterator。要避免ConcurrentModificationException,请使用Iterator.remove()。 试试吧,

Iterator<Integer> it = s.iterator();
    while(it.hasNext())
    {
        Integer val= it.next();          
        if(val>=0)
        {
            it.remove(); //Use Iterator.remove
            //s.remove(val);
            q.add(val);
        }
    }

【讨论】:

  • 不敢相信我错过了!不过还是谢谢。
【解决方案2】:

迭代时不能修改堆栈。您必须删除行 s.remove() 以防止发生此错误。发生这种情况是因为迭代器的副本现在与原始副本不同。如果您想删除任何元素并添加到队列中,可以使用以下代码:

while(!s.empty()) {
    val = s.pop();
    if(val>=0) {
        q.add(val);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-02
    • 1970-01-01
    • 2012-01-01
    相关资源
    最近更新 更多