How do I remove an object from an ArrayList in Java?

后端 未结 9 1649
面向向阳花
面向向阳花 2020-12-15 01:06

I have an ArrayList that contains some object, such as User, and each object has a name and password property. How can I

9条回答
  •  温柔的废话
    2020-12-15 01:25

    You are probably faced with the ConcurrentModificationException while trying to remove object from the List. An explanation for this exception is that the iterator of the ArrayList is a fail-fast iterator. For example, it will throw an exception (fail) when it detects that its collection in the runtime has been modified. The solution to this problem is to use the Iterator.

    Here is a simple example that demonstrate how you could iterate through the List and remove the element when specific condition is met:

    List list = new ...
    
    for (Iterator it = list.iterator(); it.hasNext(); ) {
    
        User user = it.next();
        if (user.getUserEmail().equals(currentUser.getUserEmail())) {
           it.remove();
        }
    }
    

提交回复
热议问题