for-loop minimizes the scope of the Iterator in the loop itself. What exactly does this mean?
To use an Iterator in a while , you must declare and initialize it before using the while . 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 a for loop, an Iterator declared inside the scope of the for loop, so it can only be used inside the body of this loop.
List<DataType> list = new ArrayList<DataType>(); for ( Iterator<DataType> it = list.iterator(); list.hasNext(); ) { } it.hasNext();
Should I use in-loop for while loop?
It totally depends on your needs. Usually, if you are going to use all the elements of an iterator in a single loop, it is better to use the for loop approach, and it is better to use the extended for loop, which already uses Iterator behind the scenes:
for(DataType data : list) {
In cases where you will not move through all the elements of the iterator in a loop, it would be better to use while . An example of this is the implementation of merge sorting (Note: this example is entirely for training).
source share