let's say we have a a Pencil class which has two attributes like this:
public class Pencil {
String color;
int length;
public Pencil(String c, int sh, int l) {
this.color = c;
this.length = l;
}
public String getColor() {
return color;
}
}
then we put 4 Pencil's object into a Box:
public class Box {
ArrayList<Pencil> list;
public Box() {
list = new ArrayList<Pencil>();
list.add(new Pencil("blue", 5, 10));
list.add(new Pencil("black", 5, 10));
list.add(new Pencil("brown", 5, 10));
list.add(new Pencil("orange", 5, 10));
}
}
and then we want to remove one of these objects from the list based of the value of color
:
public class TestDrive {
public static void main(String[] args) {
Box b = new Box();
ArrayList box = b.list;
Iterator it = box.iterator();
while(it.hasNext()) {
Pencil p = (Pencil) it.next();
if (p.getColor() == "black") {
box.remove(p);
}
}
}
}
seems pretty straightforward, but i'm getting Exception in thread "main" java.util.ConcurrentModificationException
. I'd appreciate it if someone could tell what I'm missing here