java错误ConcurrentModificationException

The ConcurrentModificationException is an exception that occurs when attempting to modify a collection (such as a list, set, or map) while iterating over it using an iterator or a for-each loop.

    public void deleteCustomer(String x) {
        ArrayList<String> foundCustomers = new ArrayList<>();
        for (Customer customer : customers) {
            if (customer.getFirstName().concat(",").concat(customer.getLastName()).equals(x))
            {
                customers.remove(customer);
            }
        }
    }

原因在于访问的同时进行删除

正确做法应当采用迭代器

public void deleteCustomer(String x) {
        Iterator<Customer> iterator = customers.iterator();
        while (iterator.hasNext()) {
            Customer customer = iterator.next();
            if (customer.getFirstName().concat(",").concat(customer.getLastName()).equals(x)) {
                iterator.remove();
            }
        }
    }

还得是gpt

posted @ 2023-12-01 14:02  gan_coder  阅读(13)  评论(0)    收藏  举报