I need to check through an arraylist of "tiles" and if it finds a tile that its not used yet add 4 tiles around that tile but when i add something new while checking the list it crashes. How to add objects to arraylist without crashing it while checking it?
I add one tile and then check it:
private static List<Tile> tiles = new ArrayList<Tile>();
tiles.add(new Tile(mapsize/2*tilesize, mapsize/2*tilesize));
for(Tile tile: tiles){
if(!tile.spread){
tile.spread=true;
tiles.add(new Tile(tile.position.x-tilesize, tile.position.y)); //this line crashes it
}
}
when i add something new while checking the list it crashes
With a ConcurrentModificationException
. It is expected. Apart from using an Iterator
's .remove()
you cannot modify a list like you do (not a non concurrent one like ArrayList
anyway).
You should create a new list in which you add your new tiles, then when you're done iterating, addAll this new list to the existing list:
final List<Tile> newTiles = new ArrayList<>();
for (final Tile tile: tiles) {
if (tile.spread)
continue;
tile.spread = true;
newTiles.add(new Tile(tile.position.x - tilesize, tile.position.y));
}
tiles.addAll(newTiles);
Of course, the code above supposed that your code is not called from several threads simultaneously! Or that this code is in a method protected by a lock...
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments