For example, if I were to do…
JavaScript
x
for (String s : arraylist) {
// Do something with string
}
If it isn’t possible, is there another method of traversing through some sort of collection class while controlling the iteration counter? I tried looking through the answers to this question but couldn’t think of a way that was clear to me.
Any suggestions are appreciated!
Advertisement
Answer
It depends on what you are trying to do, but you can use a while-loop
and increment the index when it’s appropriate:
JavaScript
while(i<limit){
list.get(i);
// Do something
if(someConditionMet){
i++
}
}
Or you can use a for-loop
without incrementing the index after each iteration:
JavaScript
for (int i = 0; i < 5; ) {
list.get(i);
// Do something
if(someConditionMet){
i++;
}
}
Also if the collection implements Iterable
, you can use the iterator to iterate over the collection:
JavaScript
List<Integer> list;
Iterator<Integer> iterator = list.iterator();
while(someCondition){
if(someOtherContion){
Integer next = iterator.next();
}
}