问题描述
public void kill(double GrowthRate, int Death)
{
int before = population.size();
for (PopulationMember p : population)
{
int[] probs = ProbablityArrayDeath(GrowthRate,Death,(int)p.fitness());
if (probs[RandomNumberGen.nextRandomInt(0, 99)]==0)
{
population.remove(p);
}
}
System.out.println("Intial Population: "+before+", Deaths:"+(before- population.size())+", New Population: "+population.size());
}
当我运行我的程序时第一次尝试运行代码此错误
When I run my program the first time it tries to run the code it hits this error
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextEntry(HashMap.java:793)
at java.util.HashMap$KeyIterator.next(HashMap.java:828)
at Genetics.Population.kill(Population.java:181)
at Genetics.Population.run(Population.java:47)
at Control.Main.main(Main.java:35)
有一大堆这样似乎是一个错误,通常发生在线程为什么他们尝试和并发访问相同的资源,但这是什么让我不是多线程在这个系统中。
Having goggled around a bit this seems to be an error that normally happens with threads why they try and access the same resource concurrently, but this is what getting me im not multithreading at all in this system.
有人可以解释为什么会发生这种情况,或者想到一个黑客可以绕过它。
Can someone explain why this is happening, or think of a hack to get around it
_ ^
推荐答案
您可以修改
c $ c> Iterator
(隐藏在 for-each
循环中)。
正确的方法是:
You can modify the underlying Collection
of the Iterator
(which is hidden in the for-each
loop).The proper way to do this is:
for (Iterator<PopulationMember> it = population.iterator(); it.hasNext();) {
PopulationMemeber p = it.next();
int[] probs = ProbablityArrayDeath(GrowthRate,Death,(int)p.fitness());
if (probs[RandomNumberGen.nextRandomInt(0, 99)] == 0) {
it.remove();
}
}
这篇关于非多线程程序中的java.util.ConcurrentModificationException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!