How do I remove an object from an ArrayList in Java?
Iterator<User> it = list.iterator();
while (it.hasNext()) {
User user = it.next();
if (user.getName().equals("John Doe")) {
it.remove();
}
}
Another thought: If User
class can be uniquely defined by the username and if you override equals
with something like:
public boolean equals(Object arg0) {
return this.name.equals(((user) arg0).name);
}
You can remove the User
without iterating through the list . You can just do :
list.remove(new User("John Doe"))
You could use something like this:
// If you are using java 8
userList.removeIf(user-> user.getName().equals("yourUserName"));
// With older version
User userToRemove = null;
for(User usr:userList) {
if(usr.getName().equals("yourUserName")) {
userToRemove = usr;
break;
}
}
userList.remove(userToRemove);