1

Is there any way I can use an Iterator inside another loop? I am asking this because I can't find a way to bring the iterator at the start of the list again after the first loop is done and therefore at a second loop the iter.hasNext() will give me false

Iterator iter = list.iterator();
for (int i=0;i<30;i++)
{
 while (iter.hasNext())
 {
  ...
 }

}
2
  • 2
    Uhhh... move the first line inside the for? Commented Apr 29, 2015 at 23:15
  • Well mind stops working sometimes... I don't know why I didn't think of that. Commented Apr 29, 2015 at 23:19

3 Answers 3

2
Iterator iter;
for (int i=0;i<30;i++)
{
    iter = list.iterator();
    while (iter.hasNext())
     {
      ...
     }

}
Sign up to request clarification or add additional context in comments.

Comments

0

You could just reset the iterator in the outer loop:

for (int i=0;i<30;i++) {
    Iterator iter = list.iterator();
    while (iter.hasNext()) {
        Object obj = iter.next();
    }
}

Comments

0

The iterator was consumed during first cycle of a loop (i==0). To fix the problem u need to reinitialise the item reference inside a loop. Best!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.