Good evening,
I'm trying to call the "ricolora" method on each pixel inside the arraylist (change the color of the pixel), the first method (the one with the iterator) doesn't work.
It gives me an exception (java.lang.reflect.InvocationTargetException).
The second method (for loop) works just fine. Can you please help me understand why the first method doesn't work, i thought that the for loop and the iterator were almost the same thing.
Thank you for your help.
public class DisegnoManoLibera {
protected final ArrayList<Pixel> pixel;
final public void ricolora(Color c) {
Iterator<Pixel> it = this.pixel.iterator();
int i=0;
while(it.hasNext()){
Pixel pi =(Pixel) it.next();
Pixel gi = new Pixel(pi.getX(), pi.getY(), c);
pixel.remove(i);
pixel.add(i, gi);
i++;
}
}
final public void ricolora(Color c) {
for(int i=0; i<this.pixel.size();i++){
Pixel pip = pixel.get(i);
Pixel gin = new Pixel(pip.getX(), pip.getY(), c);
pixel.remove(i);
pixel.add(i, gin);
}
}
public class Pixel {
final int x;
final int y;
final Color c;
forloop won't allow updating the collection during the iteration, which is what OP is doing. OP is just doing it the wrong way.int ivariable and accessing the list by index you've broken the whole idea ofIterators. Also, there is anIterator#Remove()method if you want to remove an element.