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

浙公网安备 33010602011771号