Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 336
Steve Benett Avatar asked Aug 13 '13 14:08

Steve Benett


1 Answers

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.

like image 69
JNL Avatar answered Sep 20 '22 23:09

JNL