Was*_*our 0 java collections arraylist concurrentmodification
我有这个方法从ArrayList 中删除特定的对象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;
}
}
Run Code Online (Sandbox Code Playgroud)
错误:
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)
Run Code Online (Sandbox Code Playgroud)
如果您需要有关我的代码的更多信息,请告诉我
添加方法
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);
}
Run Code Online (Sandbox Code Playgroud)
您正在ArrayList尝试迭代它时从中删除对象.正如其他人向你指出的那样,这不起作用并且正在给你ConcurrentModificationException.你想要这样的东西:
if(StockProducts.contains(p))
StockProducts.remove(p);
Run Code Online (Sandbox Code Playgroud)
或者,如果您真的想要遍历列表并进行更改,那么您应该可以使用ListIterator如下所示:
ListIterator<Product> iter = StockProducts.listIterator();
while(iter.hasNext()){
if(iter.next().equals(p)){
iter.remove(p);
}
}
Run Code Online (Sandbox Code Playgroud)
或者如果列表可以有多个Product具有相同结果的s getCode():
ListIterator<Product> iter = StockProducts.listIterator();
while(iter.hasNext()){
if(iter.next().getCode() == p.getCode()){
iter.remove(p);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1858 次 |
| 最近记录: |