如何从ArrayList中删除项目

时间:2014-09-25 14:14:08

标签: java arrays arraylist

您好我正在尝试创建一个地址簿并将所有条目存储到arrayList。我当前在从列表中删除项目时遇到问题。有人可以帮帮我吗。 这是我的ArrayList,其中包含我的setter / getter和构造函数

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) {

1 个答案:

答案 0 :(得分:0)

使用old for with iterator并调用iterator.remove()方法,而不是为每个循环调用a内的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()方法绕过了这个限制。