スタックでイテレータを使用しているにもかかわらず、同時変更の例外が発生します
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;
}
}
なぜ何か考えはありますか?
Stack.remove
安全ではありません。で発生ConcurrentModificationException
しIterator
ます。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);
}
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加