简体   繁体   English

Java ConcurrentModificationException与抽象超类

[英]Java ConcurrentModificationException with abstract super class

So I understand why I get the error; 所以我明白为什么会得到错误; I would like to know a work around if possible or an alternative! 我想知道一个可行的解决方法或替代方法!

So I have a class called SpriteRenderable which is used to sort and render all objects on screen, it contains the position and sprite for the instances. 因此,我有一个名为SpriteRenderable的类,该类用于对屏幕上的所有对象进行排序和渲染,其中包含实例的位置和精灵。

public static ArrayList<SpriteRenderable> spriteRenderables;

SpriteRenderable also has a static function Render(SpriteBatch batch) which loops over this list to call the update function on each one. SpriteRenderable还具有一个静态函数Render(SpriteBatch batch) ,该函数循环遍历此列表以在每个列表上调用update函数。

public static void Render() {
    spriteBatch.begin();
    for (ListIterator<SpriteRenderable> iter = 
        spriteRenderables.listIterator(); iter.hasNext();) {
        SpriteRenderable spriteRenderable = iter.next();
        spriteRenderable.update(delta);
        spriteRenderable.sprite.draw(spriteBatch);
        }
    spriteBatch.end();
}

public abstract void update();

I have another class Player which extends the SpriteRenderable class, so it's automatically added to the static ArrayList, and updated every render cycle. 我还有另一个类Player ,它扩展了SpriteRenderable类,因此它将自动添加到静态ArrayList中,并在每个渲染周期更新。 This is the same as the Gun and Bullet class as well. 这与“ GunBullet类相同。

The Gun class and Bullet class extend SpriteRenderable as well. Gun类和Bullet类也扩展了SpriteRenderable Within the Player classes update function, if (Gdx.input.isButtonPressed(Input.Buttons.LEFT)) then the Guns shoot method is called which in tern calls Bullet shot = new Bullet(); Player类更新功能中,如果(Gdx.input.isButtonPressed(Input.Buttons.LEFT))则调用Guns (Gdx.input.isButtonPressed(Input.Buttons.LEFT))方法,随后将调用Bullet shot = new Bullet(); (Gdx.input.isButtonPressed(Input.Buttons.LEFT))

This works fine until Player is updated, and the player fires the gun; 在更新播放器之前,它可以正常工作,并且播放器开火; the instantiated bullets are added to the static ArrayList while looping through itself. 实例化的项目符号会在自身循环时添加到静态ArrayList中。 Causing : 原因:

Exception in thread "LWJGL Application" java.util.ConcurrentModificationException

I've tried surrounding the foreach(SpriteRenderable) loop with a try and catch; 我试过用try和catch来包围foreach(SpriteRenderable)循环; however this ends up not rendering any of the sprites due to the exception. 但是由于异常,最终没有渲染任何精灵。

Assuming you iterate more through the list than modify it, you'd be good with CopyOnWriteArrayList . 假设您遍历列表而不是修改列表,那么使用CopyOnWriteArrayList会很好。 Any modifications during the lifetime of the iterator will not be visible to the iterator, however. 但是,在迭代器的生存期内,对其进行的任何修改都是不可见的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM