0

Hi I am trying to loop through an arraylist but get an error message. So my very specific question is, where am I doing something wrong?

Error message:

Exception in thread "main" java.util.ConcurrentModificationException at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901) at java.util.ArrayList$Itr.next(ArrayList.java:851) at main.numberOfNeighbours(main.java:130) at main.calculateNextGen(main.java:95) at main.main(main.java:30)

Code:

public static int numberOfNeighbours(boolean[][] arena, int x, int y){
    //Calculates a given cells number of neighbours.

    int height = arena[0].length;
    int width = arena.length;

    ArrayList<int[]> cors = new ArrayList<int[]>();
    for(int i = -1; i < 2; i++){
        for(int e = -1; e < 2; e++){
            int[] xy = {x+i, y+e};
            cors.add(xy);
        }
    }

//This is where I get the error
    for(int[] xy : cors){
        //Exclude cors that are out of range or the cell itself.
        if(xy[0] == -1 || xy[1] == -1 || xy[0] == width || xy[0] == height || (xy[0] == x && xy[1] == y)){
            int index = cors.indexOf(xy);
            cors.remove(index);
        }
    }

    int neighbours = 0;
    for(int[] xy : cors){
        if(arena[xy[0]][xy[1]]){
            neighbours++;
        }
    }

    return neighbours;
}

I have been googling but can't find a solution. I think my main problem is that I don't understand the error message so any help explaining that would be great.

Ivar Eriksson
  • 863
  • 1
  • 15
  • 30

1 Answers1

1

You're calling cors.remove(index); while still iterating over the list. That will mess up the indexes and throws the exception.

Miles
  • 110
  • 9