the for-loop minimizes the scope of the Iterator to the loop itself. What exactly does that mean?
To use the Iterator on the while loop, you must declare and initialize it before being using in the while loop. So, you can do this:
List<DataType> list = new ArrayList<DataType>();
Iterator<YourDataType> it = yourList.iterator();
while (it.hasNext()) {
}
it.hasNext(); //this compiles and will return false
In the for loop, the Iterator is declared to be inside the scope of the for loop, so it can be used only inside the body of this loop.
List<DataType> list = new ArrayList<DataType>();
for ( Iterator<DataType> it = list.iterator(); list.hasNext(); ) {
}
it.hasNext(); //this won't work and is a compiler error since the variable it's outside its scope
Should I use the for-loop insteed of the while-loop?
This entirely depends on your needs. Usually, if you're going to consume all the elements of the iterator in a single loop, it is better to use the for loop approach, and it will be better using the enhanced for loop that already uses Iterator behind the scenes:
for(DataType data : list) {
//...
}
In cases where you won't navigate through all the elements of the iterator in the loop, it would be better to use a while. An example of this could be implementing a merge sort (Note: this example is entirely for learning purposes).