我有这样的方法,从ArrayList中错误从ArrayList中Java中移除对象[Eclipse中]
这里删除特定对象P是我的代码:
public void removeProduct(Product p) throws StockException{
int flag=0;
for(Product i:StockProducts)
if(p.getCode()==i.getCode()){
this.StockProducts.remove(p);
flag=1;
}
if(flag==0){
StockException e = new StockException("could not remove the Product , PRODUCT IS NOT IN THE STOCK: ", p);
throw e;
}
}
错误:
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
at java.util.ArrayList$Itr.next(Unknown Source)
at Stock.removeProduct(Stock.java:29)
at Test.main(Test.java:18)
如果您需要更多关于我的代码的信息,请告诉我
添加方法
public void addProduct(Product p) throws StockException{
for(Product i:StockProducts)
if(p.getCode()==i.getCode()){
StockException e = new StockException("could not add the Product , CODE ALREADY EXIST IN STOCK: ", p);
throw e;
}
this.StockProducts.add(p);
}
你不能改变环路或使用迭代器列表..相反检查你的名单“包含”的对象,如果是,将其删除,并设置标志。 – TheLostMind
由于您正在阅读数组列表并同时从列表中删除项目,因此您正在收到该错误。使用迭代器,您不能同时执行这两个操作。 – Rahul
我不明白,我用“addProduct”方法做了同样的事情,它的工作原理 –