2014-01-20 26 views
0

我有这样的方法,从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); 
    } 
+2

你不能改变环路或使用迭代器列表..相反检查你的名单“包含”的对象,如果是,将其删除,并设置标志。 – TheLostMind

+0

由于您正在阅读数组列表并同时从列表中删除项目,因此您正在收到该错误。使用迭代器,您不能同时执行这两个操作。 – Rahul

+0

我不明白,我用“addProduct”方法做了同样的事情,它的工作原理 –

回答

5

您从ArrayList,而试图通过它来删除重复的对象。正如其他人指出的那样,这不起作用,正在给你ConcurrentModificationException。你想是这样的:

if(StockProducts.contains(p)) 
    StockProducts.remove(p); 

或者,如果你真的想通过列表进行迭代,并改变它,你应该能够使用ListIterator这样的:

ListIterator<Product> iter = StockProducts.listIterator(); 
while(iter.hasNext()){ 
    if(iter.next().equals(p)){ 
     iter.remove(p); 
    } 
} 

如果列表中可以有多个Product s的相同的结果,从getCode()

ListIterator<Product> iter = StockProducts.listIterator(); 
while(iter.hasNext()){ 
    if(iter.next().getCode() == p.getCode()){ 
     iter.remove(p); 
    } 
} 
+1

使用第一个,完美的作品:) –

2

使用iterator而迭代从列表中删除的对象。

做这样

Iterator<Product> iterator = StockProducts.iterator(); 
while(iterator.hasNext()) { 
     Product i = iterator.next(); 
     if(p.getCode()==i.getCode()){ 
      iterator.remove(); 
      flag=1; 
     } 
}