We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hi there, as title says I'm having a ConcurrentModificationException error while running my sketch. I'm working on a single channel image, red, and I'm trying to scan every pixels and putting them in different arrays based on their colour. Here's the logic of what I want to do: - loop through every pixels; -if there's no arrays yet create one and append the colour of the first pixel found and its location; -then for the second pixel found loop through the existing arrays and compare its red component to their first element (the red component). If it finds an equal value its location gets added to that array, otherwise it creates another array containing red component an location. -And so on...
So let's say I have a 10x10 image and 50 pixels have red value == 255 and the other 50 == 100 my result should be: array1 = [255, pixelLocation,pixelLocation,pixelLocation, ......] array2 = [100, pixelLocation,pixelLocation,pixelLocation, ......]
I know what ConcurrentModificationException error means but I'm finding it hard to fix, it seems all logic to me.
Here's the sketch:
import java.util.List;
PImage img;
final List<IntList> arrayOfLists = new ArrayList();
void setup() {
size(600,600);
img = loadImage("sourceimages/sample_002_Rchan.jpg");
image(img,0,0);
loadPixels();
for(int x = 0; x < width; x++){
for(int y = 0; y < height; y++){
int loc = x + y * width;
//GET R COMPONENT
float r = red(img.pixels[loc]);
if(arrayOfLists.size() == 0){ // IF ARRAY OF LISTS DOES NOT CONTAIN ANY LIST
IntList iR = new IntList(int(r)); // create a new list
iR.append(int(r)); //append pixel colour
iR.append(loc); //append pixel location
arrayOfLists.add(iR); //add list to ARRAY OF LISTS
}//END OF IF
else{ //LOOP THROUGH arrayOfLists
for(IntList list : arrayOfLists) {
if(int(r) == list.get(0)) {
list.append(loc);
} // END OF IF
else {
IntList iR = new IntList(int(r)); // create a new list
iR.append(int(r)); //append pixel colour as first element
iR.append(loc); //append pixel location
arrayOfLists.add(iR); //add list to ARRAY OF LISTS
} // END of else
} // END of for lists in arrayOfLists
}//END OF ELSE
} // END of for X
} // END of for Y
println("NUM OF ARRAYS: ",arrayOfLists.size());
println("ITEMS IN FIRST ARRAY:", arrayOfLists.get(0));
}//END setup
Answers
Don't add things to the list while iterating on it.
A possible way to do this is:
Notes:
Thanks PhiLho, your code works and I'm getting the expected results :D I'm not able to accept your answer, probably because you left a comment.