如何在不使用ConcurrentModificationException的情况下使用ArrayList?

lia*_*dee 1 java arrays collections arraylist

JAVA

我的游戏中有一个ArrayList来存储游戏中的所有粒子.我有一个访问ArrayList来更新物理的更新方法,我有一个访问ArrayList的渲染方法来渲染屏幕上的粒子,还有一个MouseClick侦听器,当它检测到MouseClick时,它会向ArrayList添加一个新粒子.

我的问题是我不断收到java.util.ConcurrentModificationException.这是因为当我同时点击它渲染时,两个方法都试图访问ArrayList.是否有同时访问ArrayList的解决方案(不同的数据类型?).

一些代码可以帮助 -

ArrayList声明

ArrayList<Particle> ParticleList = new ArrayList<Particle>();
Run Code Online (Sandbox Code Playgroud)

粒子类定义

public class Particle {

int x;
int y;
Color colour;
int type;
//0:wall
public Particle(int x,int y,Color colour,int type)
{
    this.x = x;
    this.y = y;
    this.colour = colour;
    this.type = type;
}`
Run Code Online (Sandbox Code Playgroud)

渲染方法

for(Particle e : this.ParticleList)
{
g.fillRect(e.x, e.y, 1, 1);
}
Run Code Online (Sandbox Code Playgroud)

Boz*_*zho 5

更新:似乎你没有多线程访问,所以我的原始答案不成立(我会保留它为了完整性)

ConcurrentModificationException只有在迭代时从集合中添加或删除时才会出现单个线程.要解决此问题,请创建一个新集合,该集合是第一个集合的副本,然后添加到该集合中.


如果您的写入(点击)小于读取次数,那么您可以使用 CopyOnWriteArrayList

否则,您必须在迭代时进行同步.或者获得副本(List copy = new ArrayList(original))