VOOZH about

URL: https://www.geeksforgeeks.org/java/generic-for-loop-in-java/

⇱ Generic For Loop in Java - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Generic For Loop in Java

Last Updated : 7 Dec, 2022

When we know that we have to iterate over a whole set or list, then we can use Generic For Loop. Java's Generic has a new loop called for-each loop. It is also called enhanced for loop. This for-each loop makes it easier to iterate over array or generic Collection classes.

In normal for loop, we write three statements :

for( statement1; statement 2; statement3 )
{
 //code to be executed 
}

Statement 1 is executed before the execution of code, Statement 2 states the condition to be satisfied to execute the code and Statement 3 gets executed after the execution of the code block.

But if we look into the Generic For loop or for-each loop,

The generic for loop consists of three parameters :

  • Iterator function: It gets called when the next value is needed. It receives both the invariant state and control variable as parameters. Returns nil signals for termination.
  • Invariant state: This doesn't change during the iteration. It is basically the subject of the iteration such as String, table or user data.
  • Control variable: It represents the initial value of the iteration.

Syntax 

for( ObjectType variable : iterable/array/collections ){

 // code using name variable
}

Equivalent to 

for( int i=0 ; i< list.size() ; i++) {

 ObjectType variable = list.get(i);

 // statements using variable
}

Example: 


Output
379

Example: Showing that 


Output
key :Quiz
key :Github
key :Practice
key :GFG
value :www.geeksforgeeks.org
value :www.github.com
value :practice.geeksforgeeks.org
value :geeksforgeeks.org

Limitations of Generic For loop or for-each loop:

1. Not appropriate when we want to modify the list.

for( Integer var : arr)
{
 // only changes the var value and not the value of the data stored inside the arr
 var = var + 100; 
} 

 2. We cannot keep track of the index.

for( Integer var : arr){
 
 if(var == target)
 { 
 // don't know the index of var to be compared with variable target 
 return **; 
 } 
} 

4. Iterates a single step in forward direction only.

// This cannot be converted to Generic for loop
for( int i = n-1 ; i >= 0 ; i-- ) {

 // code
 
} 

4. Cannot process two decision-making statements at once.

// This loop cannot be converted to Generic for loop
for( int i = 0; i < arr.length; i++ ) {

 if( arr[i]==num )
 return **;
} 
Comment
Article Tags: