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?
The difference is basically
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With