user2973447 user2973447 - 7 months ago 22
Java Question

Removing a user from an arraylist by username

I am using blueJ to write this. What I am trying to do is write a method called removeUser() in the userGroup class which takes a String as a parameter which is the username I want to remove. Using an Iterator, iterate over the list until I find the user with that username and remove them. My code is:

package user;
public class User{
public enum UserType{
ADMIN, EDITOR, USER;
}

private String id;
private UserType userPermissions;
private String actualName;

public User(String username, UserType userType, String name){
id = username;
userPermissions = userType;
actualName= name;
}

public String getUsername(){
return id;
}

public UserType getUserType(){
return userPermissions;
}

public String getName(){
return actualName;
}

public void setUserType(UserType input){
userPermissions = input;
}
}


and the userGroup class is:

package user;
import java.util.*;
import user.User.UserType;

public class UserGroup{

private ArrayList<User> people;

public UserGroup(){
people = new ArrayList<User>();
}

public void addSampleData(){
people.add(new User("jar1g13", UserType.ADMIN,"Jonny"));
people.add(new User("ao9", UserType.EDITOR,"Aniruddh"));
people.add(new User("pe6", UserType.USER,"Peter"));
people.add(new User("mat73", UserType.USER,"Matthew"));
people.add(new User("ora69", UserType.EDITOR,"Oranthi"));
people.add(new User("ben12", UserType.USER,"Benedict"));
people.add(new User("cam30", UserType.ADMIN,"Cambyse"));
people.add(new User("are20", UserType.USER,"Alex"));
people.add(new User("lim19", UserType.USER,"Liam"));
people.add(new User("ada13", UserType.EDITOR,"Adam"));
}

public User getUser(int idx){
return people.get(idx);
}

public void printUsernames(){
for (User user: people){
System.out.printf("%s %s\n", user.getUsername(), user.getUserType());
}
}

public void removeFirstUser(){
people.remove(0);
}

public void removeLastUser(){
people.remove(people.size()-1);
}

public void removeUser(String username){
people.remove(username);
}

}


This all compiles fine but when I run the removeUser method it doesn't seem to remove anything from the array!

ajc ajc
Answer
public void removeUser(String username) {
     Iterator<User> itr = people.iterator();
     while (itr.hasNext()) {
          Users element = (User) itr.next();
          if (element.getUsername().equals(username)) {
               itr.remove(); // REMOVE THIS FROM Iterator
          }
     }
}