Difference between a for-loop and a while-loop using an Iterator

iterator, java, loops, performance

Solution

The difference is basically

In for loop:

for (Iterator<DataType> it = list.iterator(); list.hasNext(); ) 

In this case, you are declaring the Iterator object locally and it will be `eligible for GC(garbage collection) after the for loop`.

In while loop,

`while (it.hasNext())` since you have declared the object Iterator outside a loop. So its scope is may be `the entire program` or the `method it is in`. Or incase if it is referenced anywhere, so it wont be eligible for GC.

Hope this helps.

Problem

Iterator using while-loop: ``` List<DataType> list = new ArrayList<DataType>(); Iterator<YourDataType> it = yourList.iterator(); while (it.hasNext()) // Do something ``` Iterator using for-loop: ``` List<DataType> list = new ArrayList<DataType>(); for ( Iterator<DataType> it = list.iterator(); list.hasNext(); ) // Do something ``` I've read that the for-loop minimizes the scope of the Iterator to the loop itself. What exactly does that mean? Should I use the for-loop insteed of the while-loop?

Original source