ArrayList with objects

2230 views java
10

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);
            }

answered question

why are you adding currentproject just update that object

2 Answers

10

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);
        } 
    }

posted this
4

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();
    }
}

posted this

Have an answer?

JD

Please login first before posting an answer.