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

后端 未结 9 1643
面向向阳花
面向向阳花 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:34

    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"))
    
    0 讨论(0)
  • 2020-12-15 01:34

    Just search through the ArrayList of objects you get from the user, and test for a name equal to the name you want to remove. Then remove that object from the list.

    0 讨论(0)
  • 2020-12-15 01:34

    Your code might look like this:

    List<User> users = new ArrayList<User>();
    
    public void removeUser(String name){
        for(User user:users){
            if(user.name.equals(name)){
                users.remove(user);
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题