Collections

  • A collection in Java is a group of objects with an iteration operation

  • The iteration operation is a way to access all items stored in a collection:

An array is a collection

  • A array in Java is (an example of) a collection:

  • Therefore:   arrays have an iteration operation to access all items stored in an array:

Iterators and the for-each loop

  • The for-each loop statement:

    • The for-each loop statement in Java provides a convenient way to use the iterator of a collection to access the items in a collection

  • The syntax of the for-each loop statement is:

        for (elementType e: collectionRefVar) 
        {
           // Use  the element e
        } 

    Example:

        String[] words = { "abc", "klm", "xyz"};  // words is a collection
    
        for (String e: words) 
        {
           System.out.println(e); // Prints: abc klm xyz
        } 

DEMO: demo/08-array/04-for-each-loop/Demo1.java

Example for-each loop    sum all values in array

  • Here is how to sum all the elements in the array myList using a for-each loop:

       public static void main(String[] args)
       {
           double[] myList = { 1, 2, 3, 4, 5, 6};
           double   sum;
    
           // Compute sum = sum all elements in array myList
    
           sum = 0;
           for ( double e: myList )
               sum = sum + e;
                
           System.out.println("sum = " + sum);
       } 

  • Notes:

      • The for-each loop do not use an index to access the array elements

      • You cannot update array elements with a for-each loop

DEMO: demo/08-array/04-for-each-loop/SumArray.java