AP Computer Science --- Haas --- ForEachLoop



/**
 * The foreach statement allows you to iterate through all the 
 * items in a collection. Is it a new feature of J2SE5.0.
 * 
 *   for (type value : container) statement
 */
import java.util.*;

public class ForEachLoopArrayList {
  public static void main(String args[]) {

    /**
     * Example 1
     */  
    int[] nums = {5, 1, 3, 8};
    
    for (int x : nums) {  
      System.out.println(x + " ");
    }
     
    
    /**
     * Example 2
     */
    ArrayList< String > fruits = new ArrayList< String >();
    fruits.add("orange");
    fruits.add("apple");
    fruits.add("pear");
    fruits.add("banana");
    
    for (String i : fruits) {  
      System.out.println(i + " ");
    }

    // ERROR >>> can't modify with for-each loop
   for (String x : fruits) {  
      if (x.equals("apple")) {
          fruits.remove(0);   
      }
   }
    
  }
}