Do you use a foreach loop or a for loop for iterating groups in Java?

  • 2020-04-01 03:57:39
  • OfStack

Starting with JDK1.5, the new function Foreach, which is a shorthand form of the for loop traversing data, still USES the keyword for, but with a different parameter format. Its detailed usage is:


for(Type e:collection){ 
// The variable e The use of } 

Parameter description:

E: its Type Type is the Type of the element value in a collection or array. The parameter is an element in a collection or array collection.
Collections: the collection or array to traverse, which can also be an iterator.

In the loop body, use the parameter e, which is the element value that foreach takes from the collection or array and iterator, and the element value is traversed from beginning to end.
Specific examples:


//The following two packages for util must be imported :ArrayList,List;
import java.util.ArrayList; 
import java.util.List; 
public class Foreach { 
  public static void main(String[] arg){ 
    List<String> list = new ArrayList<String>(); //Create a List collection
    list.add("abc"); //Initializes the list collection
    list.add("def"); 
    list.add("ghi"); 
    list.add("jkl"); 
    list.add("mno"); 
    list.add("pqr"); 
    System.out.print("Foreach Traverse the collection : nt");  
    for(String string:list){          //Traversing the List collection
      System.out.print(string);        //Outputs the element values of the collection
    } 
    System.out.println(); 
    String[] strs = new String[list.size()];    
    list.toArray(strs);             //Create an array
    System.out.println("Foreach Through the array :nt"); 
    for(String string: strs){          //Through the array
      System.out.print(string);        //Output array element values
    } 
  }  
} 

Conclusion:

Previous versions of the JDK used a for loop to traverse collections, arrays, and iterators, which required the creation of index variables and conditional expressions, which caused code clutter and increased the chance of errors. And in each loop, the index variable or iterator appears three times, with two chances for errors. There is also a performance penalty, which is slightly behind the foreach loop. So Foreach loops are recommended for traversing data sets.


Related articles: