1

Currently I am writing a program that must iterate through and arraylist inside of a for loop which looks like this.

List<Integer> currentLevel = new ArrayList<Integer>();
List<Integer> nextLevel = new ArrayList<Integer>();
Iterator<Integer> it = currentLevel.iterator();
currentLevel.add(1);

for(x=0;x<20;x++){
    while(it.hasNext()){
        int element = it.next();
        nextLevel.add(element*2);
        if(element%6 == 4){
            nextLevel.add((element-1)/3);
        }
    }
    currentLevel.clear();
    currentLevel.addAll(nextLevel);
    nextLevel.clear();
}

With this code it seams that it only goes through the while loop once. Is this because after the first loop it only adds one number to the nextLevel array and the currentLevel array has the same amount of indexes as before? Or is it something that I am leaving out? If I try to add additional elements to the nextLevel array after the while loop it gives me an error at the line

int element = it.next();
coopf
  • 59
  • 5
  • What are you trying to have this code do? Without knowing what you are trying to do its not possible to know what the code should look like. – ams Feb 11 '12 at 00:07
  • I am trying to make a reverse Collatz web for a math project, if you would like to see some code look here http://stackoverflow.com/questions/9186198/java-reverse-collatz-web#comment11558888_9186198 – coopf Feb 11 '12 at 01:05
  • Wait, would it fix my problem if I just did the iteration in a different method that would be called from inside a for loop? – coopf Feb 11 '12 at 01:14
  • It does appear that making a different method that would do the iteration and calling it from a for loop wouldn't cause an error. – coopf Feb 11 '12 at 04:03

1 Answers1

3

You're entering the for loop several times, but can only enter the while loop on the first pass through the for loop.

The iterator, it is defined outside the for loop and only assigned once.

The first time through the for loop you enter a while loop:

while(it.hasNext()){
    int element = it.next();
    ...
}

which completely exhausts the iterator. Every subsequent time through the for loop, it.hasNext() is false, so the while loop does nothing.

You're also trying to re-use nextLevel and currentLevel, but those are only assigned once. So currentLevel will only contain the last set of elements added to nextLevel.

If I try to add additional elements to the nextLevel array after the while loop it gives me an error at the line

You are probably getting a concurrent modification exception. You can not use an iterator for a list after you modify it. https://stackoverflow.com/a/1496206/20394 explains how to deal with these problems.

Community
  • 1
  • 1
Mike Samuel
  • 118,113
  • 30
  • 216
  • 245