我试图遍历我的ArrayList并找到一个值,该值等于我使用while循环为其设置的条件。一旦程序遍历用户并找到与条件匹配的值,我试图让它从列表中删除该用户。一切似乎都运行正常,但它似乎没有从数组列表中删除任何东西。这是代码:
主要课程
package main;
public class Main{
public static void main(String[] args) {
System.out.println("****************For loop****************");
for (int counter=2; counter<=40; counter+=2) {
System.out.println(counter);
}
System.out.println("****************While loop****************");
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();
userGroupObject.removeFirstUser();
userGroupObject.removeLastUser();
userGroupObject.removeUser();
System.out.println("***********Number of users Array List***********");
System.out.println(userGroupObject.userGroup.size());
System.out.println("***********User's details***********");
for (User curUser : userGroupObject.getUserGroup())
{
System.out.println(curUser.toString());
} }
}
}
UserGroup类(用于制作数组列表并执行函数)
package main;
import java.util.ArrayList;
import java.util.Iterator;
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"));
addUser(new User("ohw1237", "Staff", "Oliver"));
addUser(new User("ahs1213", "Student", "Jordon"));
addUser(new User("tqn1294", "Student", "Taylor"));
}
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);
}
public void getArrayListSize() {
userGroup.size();
}
public void removeLastUser() {
userGroup.remove(4);
}
public void removeUser() {
Iterator<User> it = userGroup.iterator();
while (it.hasNext()) {
User xxx = it.next();
if (xxx.equals("jks1g26")) {
it.remove();
}
}
}
}
用户类(定义用户的详细信息)
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;
}
}
感谢任何帮助。