You are deleting an object from the ArrayList
while trying to iterate through it. As others have pointed out to you, this doesn't work and is giving you the ConcurrentModificationException
. You want something like this:
if(StockProducts.contains(p))
StockProducts.remove(p);
Alternatively, if you really want to iterate through the list and change it, you should be able to use a ListIterator
like this:
ListIterator<Product> iter = StockProducts.listIterator();
while(iter.hasNext()){
if(iter.next().equals(p)){
iter.remove(p);
}
}
or if the list can have multiple Product
s with the same result from getCode()
:
ListIterator<Product> iter = StockProducts.listIterator();
while(iter.hasNext()){
if(iter.next().getCode() == p.getCode()){
iter.remove(p);
}
}