0

I have a class UserGroup which has an ArrayList userList. I make a 1st instance of the class called 'myUserGroup' and fill it with 10 elements then i make a 2nd called 'administrators'. I want to iterate through the 'myUserGroup' arraylist and if the element is equal to "admin" add it to the 'administrators' arraylist.

Here's the UserGroup class:

public class UserGroup {

    ArrayList<User> userList;

    UserGroup(){
        userList = new ArrayList<User>();

    public Iterator<User> getUserIterator() {
        Iterator<User> iterate = userList.iterator();
        return iterate;
    }

Here's the class in which i'm trying to add the elements to the 2nd UserGroup arraylist:

public class Main {

public static void main(String[] args) {

    UserGroup myUserGroup = new UserGroup();

    myUserGroup.addSampleData();

    UserGroup administrators = new UserGroup();

    while(myUserGroup.getUserIterator().hasNext()) {

        if(myUserGroup.getUserIterator().next().getUserType().equals("admin")) {

            administrators.userList.add(myUserGroup.getUserIterator().next());
        }
    }
2
  • Call .next() only once within the loop. Commented Oct 26, 2017 at 23:49
  • try transpose ["1 5","2 4","3 3","4 2","5 1"]. Commented Mar 12, 2019 at 16:35

1 Answer 1

1

A couple problems:

  1. I think you're getting a new iterator on each loop.
  2. You call next() twice when you intend to get the same object, getting two subsequent objects.

Try this instead of your while loop:

for (User u : myUserGroup.userList) {
  if (u.getUserType().equals("admin")) {
    administrators.userList.add(u);
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.