如何从数组列表中删除用户?

时间:2016-11-04 23:19:07

标签: java arraylist

package main;
import java.util.ArrayList;

public class UserGroup {

  ArrayList<User> userGroup = new ArrayList<>();
  User userOne;
  public UserGroup() {
    addUser(new User("lnb1g16", "Student", "Lee"));
    addUser(new User("hpf1g17", "Staff", "Harry"));
    addUser(new User("jks1g25", "Student", "Jordon"));
  }

  public void addUser(User inUser) {
    //userGroup.add(new User("LeeB123", "Staff", "Lee"));
    userGroup.add(inUser);
  }

  public ArrayList<User> getUserGroup() {
    return userGroup;
  }

  public void removeFirstUser() {
    userGroup.remove(0)
  }
}

我尝试创建一个删除第一个用户并且似乎正在编译的方法,但在编译程序时实际上并没有删除用户。关于如何解决这个问题的任何想法都会很棒,谢谢。

调用程序的主要方法

package main;

public class Main{
  public static void main(String[] args) {
    for (int counter=2; counter<=40; counter+=2) {
      System.out.println(counter);
    }
    System.out.println("For loop complete.");

    int counter = 1;
    int increment = 2;
    int loopexeccounter = 0;
    while (counter <= 500) {
      loopexeccounter = loopexeccounter + 1;
      System.out.println(counter);
      counter = counter + increment++;
    }
    System.out.print("This loop iteratted "+loopexeccounter+" times.\n");

    {
      //public User callUserGroup;   
      UserGroup userGroupObject = new UserGroup();

      for (User curUser : userGroupObject.getUserGroup()) {
        System.out.println(curUser.toString());
      }
    }
  }
}

声明用户详细信息的用户方法

package main;

class User {

  String username;
  String userType;
  String name;

  User(String username, String userType, String name) {
    this.username = username;
    this.userType = userType;
    this.name = name;
  }

  public String getUsername() {
    return username;
  }

  public String getUserType() {
    return userType;
  }

   public String getName() {         
     return name;
  }

   public String setUserType(String admin) {
     return userType = admin;
   }

   @Override
   public String toString() {
     return username + " " + userType;
   }  
}

1 个答案:

答案 0 :(得分:0)

它运作良好:

`  public static void main(String[] args) {
    UserGroup MyUser = new UserGroup();
    for (User curUser : MyUser.getUserGroup()) {
        System.out.println(curUser.toString());
      }
    MyUser.removeFirstUser();
    System.out.println("your user removed!");
    for (User curUser : MyUser.getUserGroup()) {
        System.out.println(curUser.toString());
      }
  }`

结果:

`User@4554617c 1
User@74a14482 2
User@1540e19d 3
your user removed!
User@74a14482 1
User@1540e19d 2`