2014-09-25 187 views
-1

嗨我想創建一個通訊簿並將所有條目存儲到一個arrayList。我目前從列表中刪除項目時出現問題。有人可以幫幫我嗎。 這裏是我的ArrayList其中包含我的setter/getter和構造如何從ArrayList中刪除項目

List<AddressBook> addToList = new ArrayList<AddressBook>(); 

這是我從列表中刪除的項目代碼:

public class DeleteEntry { 
    Scanner scanner = new Scanner(System.in); 

    public void deleteEntry(List<AddressBook> addToList){ 
     System.out.println(" Please input name to delete: "); 
     String name = scanner.next(); 
     for (AddressBook item : addToList) { 
      if (name.equalsIgnoreCase(item.getName())){ 
       addToList.remove(item); 
       System.out.println("Item removed"); 
      }else { 
       System.out.println("name not found"); 
      } 
     } 
    } 

是我得到的錯誤是

Exception in thread "main" java.util.ConcurrentModificationException 
    at java.util.ArrayList$Itr.checkForComodification(Unknown Source) 
    at java.util.ArrayList$Itr.next(Unknown Source) 
    at addressbook.jedi.DeleteEntry.deleteEntry(DeleteEntry.java:12) 
    at addressbook.jedi.MainAddressBook.main(MainAddressBook.java:29) 

第12行是

for (AddressBook item : addToList) { 
+0

使用迭代器... – subash 2014-09-25 14:16:10

回答

0

使用舊與迭代器和調用iterator.remove()方法,而不是調用刪除裏面每個循環

for (Iterator<AddressBook> it = addToList.iterator(); it.hasNext();) { 
    AddressBoook item = it.next(); 
    if (name.equalsIgnoreCase(item.getName())){ 
     it.remove(); 
     System.out.println("Item removed"); 
    } else { 
     System.out.println("name not found"); 
    } 
} 

ArrayList的迭代器是快速失敗的,這意味着集合中的任何變化進行在獲取迭代器後,訪問下一個元素時將導致ConcurrentModificationExceptioniterator.remove()方法繞過該限制。