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();
You’re entering the
forloop several times, but can only enter thewhileloop on the first pass through theforloop.The iterator,
itis defined outside theforloop and only assigned once.The first time through the
forloop you enter awhileloop:which completely exhausts the iterator. Every subsequent time through the
forloop,it.hasNext()is false, so thewhileloop does nothing.You’re also trying to re-use
nextLevelandcurrentLevel, but those are only assigned once. SocurrentLevelwill only contain the last set of elements added tonextLevel.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.