for the difference between foreach

First talk about for circulation:

  Format: for (;;) {};

. 1  public  static  void main (String [] args) {
 2          List <String> ARR = new new the ArrayList <String> ();
 . 3          arr.add ( "Hello" );
 . 4          arr.add ( "Good I" );
 5          arr.add ( "Hello everyone" ); 
 . 6          for ( int I = 0; I <arr.size (); I ++ ) {
 . 7              System.out.println (arr.get (I));     // to get the list of The method of the get element requires     
8          }
 9      }

Then look at the foreach loop

  also called for enhanced foreach loop, foreach format:

    for (element type elements: traverse the array (set)) {

      // statement

    }

. 1  public  static  void main (String [] args) {
 2          List <String> ARR = new new the ArrayList <String> ();
 . 3          arr.add ( "Hello" );
 . 4          arr.add ( "Good I" );
 5          arr.add ( "Hello everybody" );
 6          for (String str: arr) {                     // str here is to get the value of each cycle of arr 
7                  System.out.println (str);                // equivalent STR ARR = String [I] 
. 8          }
 . 9      }

to sum up:

  foreach does not support adding delete operations in a loop, because when using foreach loop through the array has been locked can not be changed, otherwise they will be reported java.util.ConcurrentModificationException exception.

  foreach suitable only for collection or array traversal, for the more complex effect cycle.

  foreach array or collection can not be modified, if you want to modify is necessary to use a for loop.

  So after comparing the for loop is more flexible.

Guess you like

Origin www.cnblogs.com/HuiH/p/11665536.html