0

I have an ArrayList filled with objects "Project" called projectsCurrent. Each project has its name, state, manDays etc.

I wanna iterate through this list and on each project check if (manDaysDone >= manDays). If it does, than the project is done and I wanna change its state, remove it from the list and add it to another one (projectsDone).

When I try to use Iterator to achieve my goal, it seems like the link to the current project is lost inside the iteration, for example, in this code, an NoSuchElementException is raised inside the if condition:

Iterator<Project> i = projectsCurrent.iterator();
while (i.hasNext()){
    if (i.next().getManDaysDone() >= i.next().getManDays()){
        i.next().setState(ProjectState.DONE);
    } 
}

Just to make clear what I want to achieve. The following for loop does the job, but of course later I get the ConcurrentModificationException:

for (Project currentProject : projectsCurrent){
    if (currentProject.getManDaysDone() >= currentProject.getManDays()) {
        currentProject.setState(ProjectState.DONE);
        projectsDone.add(currentProject);
        this.budget += currentProject.getPrice();
        projectsCurrent.remove(currentProject);
    }
}
1
  • why are you adding currentproject just update that object Commented Nov 6, 2018 at 7:47

2 Answers 2

5

You call next three times in the loop. Each next will move the iterator forward. I guess that causes the NoSuchElementException

  while (i.hasNext()){
        Project project = i.next();
        if (project.getManDaysDone() >= project.getManDays()){
            project.setState(ProjectState.DONE);
        } 
    }
Sign up to request clarification or add additional context in comments.

2 Comments

The same error is raised on the line where Im assigning the value of i.next() to project. When I run the code in debugger I can see that i.next() has the value of the right object at that time.
I started the whole project again it works now, there must had been a mistake somewhere else. Thank you very much.
1

Only one note. You're planning to remove items randomly from the list. ArrayList implementation is not good for it. You should use LinkedList instead.

To correctly remove element from the List, you have to manually get Iterator and call it.remove() to remove it. (When you try to remove using within for(...), you get concurrent modification exception, because you have to use same iterator to iterate and to remove).

List<Project> projects = new LinkedList<>();
Iterator<Project> it = projects.iterator();

while (it.hasNext()) {
    String project = it.next();

    if (project.getManDaysDone() >= project.getManDays()) {
        project.setState(ProjectState.DONE);
        it.remove();
    }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.