Java

TOPIC 23 – ENHANCED FOR LOOP

 

LESSON NOTE

 

 

ITERABLE INTERFACE

 

Data structures in the Java Collections implement the Collection interface and the Collection interface implements the Iterable interface.

The iterable interface is a special interface that allows you to use a special for loop that is often called the enhanced for loop. 

 

The enhanced for loop simply allows for a simpler way to go through a collection of elements. Regular arrays also implement Iterable allowing us to use the enhanced for loop to go through each array element.

 

Note: We can also use the enhanced for loop on regular arrays.


EXAMPLE

The example below shows the enhanced for loop in action.  The temporary variable x refers to each element in arr one after the other.  So in the first pass inside the loop, x refers to arr[0].  In the next pass, it refers to arr[1].  And then, arr[2].  And so on till it has covered every element in the array.

 

 

MODIFYING THE DATA STRUCTURE

 

If you attempt to remove items from a data structure while inside an enhanced for loop, it will cause a concurrent error.  You should use a regular for loop for this.