Enhanced For Loop

As we know the basic for loop is used for iteration purpose. The basic for loop was extended in Java 5 to make iteration over arrays and other collections more convenient. This newer for statement is called the enhanced for or for-each.

It's commonly used to iterate over an array or a Collections class (eg, ArrayList).


For example:

// Enhanced For-each loop

Collection nameList = new ArrayList();
nameList.add("Amit");
nameList.add("Ashish");
nameList.add("Saurabh");
for (String name : nameList) {
       //code here
}

Advantages of enhanced for loop over traditional for loop

Iterator disadvantages removed

Iterator variable occurs three times per loop is more error prone as compared to enhanced for loop.

For example:

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class EnhanceForLoop {

		public static void main(String[] args) {
			List<String> myList = new ArrayList<String>();
			myList.add("Java");
			myList.add("Oracle");
			myList.add(".Net");
			myList.add("SQL");
			
			System.out.println("Using the iterator  with traditional for loop");
			for(Iterator itr = myList.iterator() ;itr.hasNext(); ){
				System.out.println(itr.next());
			}
			
			System.out.println("Using the iterator  with enhanced for loop");
			for(String lst : myList){
				System.out.println(lst);
			}
		}
	
}

Simpler when using nested loops

Let us take an example using basic for loop to iterate nested loop. Using below code we tried to map each game with each player.

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

class GameMapper{
	String player;
	String game;
	
	public GameMapper(String player, String game) {
		this.player = player;
		this.game = game;
	}
	
}
public class EnhanceForLoop {

		public static void main(String[] args) {
			List<String> player = new ArrayList<String>();
			player.add("Amit");
			player.add("Ashish");
			player.add("Saurabh");
			
			List<String> game = new ArrayList<String>();
			game.add("Java");
			game.add(".Net");
			game.add("Oracle");
			
			List<GameMapper>  mapperObj = new ArrayList<GameMapper>();
			
			for(Iterator studentItr = player.iterator() ;studentItr.hasNext(); ){
				for(Iterator gameItr = game.iterator() ;gameItr.hasNext(); ){
					mapperObj.add(new GameMapper(,(String)gameItr.next()));
				}
				
			}
			System.out.println("Size of Mapper Object ="+mapperObj.size());
		}
	
}

But actually we found the output different than what was expected. Let us have a look of the size of the list created i.e mapperObj.

Size of Mapper Object = 3

Let us understand why it happened. The problem is that the next method is called too many times on the iterator for the outer collection i.e studentItr. The problem can be fixed by calling iterator of outer loop outside the inner loop and store it in any variable to be used in an inner loop.

class GameMapper{
	String player;
	String game;
	
	public GameMapper(String player, String game) {
		this.player = player;
		this.game = game;
	}
	
}
public class EnhanceForLoop {

		public static void main(String[] args) {
			List<String> player = new ArrayList<String>();
			player.add("Amit");
			player.add("Ashish");
			player.add("Saurabh");
			
			List<String> game = new ArrayList<String>();
			game.add("Java");
			game.add(".Net");
			game.add("Oracle");
			
			List<GameMapper>  mapperObj = new ArrayList<GameMapper>();
			
			for(Iterator studentItr = player.iterator() ;studentItr.hasNext(); ){
			    String tempPlayerVal = (String)studentItr.next();
				for(Iterator gameItr = game.iterator() ;gameItr.hasNext(); ){
					mapperObj.add(new GameMapper(tempPlayerVal,(String)gameItr.next()));
				}
				
			}
			System.out.println("Size of Mapper Object ="+mapperObj.size());
		}
	
}


Now the output of above code is

Size of Mapper Object = 9

And that is what we expected, but isn't the code nasty. We have to create an additional local variable to store the value. Let us solve this issue using enhanced for loop

class GameMapper{
	String player;
	String game;
	
	public GameMapper(String player, String game) {
		this.player = player;
		this.game = game;
	}
	
}
public class EnhanceForLoop {

		public static void main(String[] args) {
			List<String> player = new ArrayList<String>();
			player.add("Amit");
			player.add("Ashish");
			player.add("Saurabh");
			
			List<String> game = new ArrayList<String>();
			game.add("Java");
			game.add(".Net");
			game.add("Oracle");
			
			List<GameMapper>  mapperObj = new ArrayList<GameMapper>();
			
			for(String playerVal : player){
				for(String gameVal : game){
					mapperObj.add(new GameMapper(playerVal,gameVal));
				}
				
			}
			System.out.println("Size of Mapper Object ="+mapperObj.size());
		}
	
}

The code is much simpler to implement, less error prone and easy to maintain.

Limitations

  • Multiple Iteration of collection objects in one for each loop is not possible.
  • You cannot remove elements while iteration in collection.
  • You cannot replace any element while iteration as you don't have control over the index of the collection.
Article tagged as
Author
Author: Amit Gupta
Published On: 05/09/2015
Last revised On: 13/11/2015
View all articles by Amit Gupta

Share this post

Comments

Comments
comments powered by Disqus

Navigation

Social Media