Search code examples
javafor-loopcopyonwritearraylist

CopyOnWriteArrayList size changing


When each the methods render, update and majorUpdate that all access the same CopyOnWriteArrayList are run render works fine, but update and majorUpdate print that the length of the CopyOnWriteArrayList is 0. Here is the code:

package main.world.layer;

import main.world.tile.ITile;
import org.newdawn.slick.Graphics;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

public class Layer {
    private List<ITile> tiles = new CopyOnWriteArrayList<ITile>();

    public void add(ITile tile){
        tiles.add(tile);
    }

    public void remove(ITile tile){
        tiles.remove(tile);
    }

    public void render(ITile tile, Graphics graphics){
        tile.render(graphics);
    }

    public void render(Graphics graphics){
        for(ITile tile : tiles){
            render(tile, graphics);
        }
    }

    public List<ITile> getTiles() {
        return tiles;
    }

    public void majorUpdate(ITile tile){
        tile.onMajorUpdate();
    }

    public void majorUpdate(){
        System.out.println("MAJOR UPDATE! " + tiles.size());
        for(ITile tile : tiles){
            majorUpdate(tile);
            System.out.println("major update");
        }
    }

    public void update(ITile tile, int delta){
        tile.update(delta);
    }

    public void update(int delta){
        System.out.println("update " + tiles.size());
        for(ITile tile : tiles){
            update(tile, delta);
            System.out.println("update");
        }
    }
}

Solution

  • If the size is printing as zero, then the tiles you are printing for is zero. Most likely you are printing the size for one list while doing render, update, majorUpdate on another.