Display list contents with enhanced for statement - Java Language Basics

Java examples for Language Basics:for

Description

Display list contents with enhanced for statement

Demo Code

import java.util.ArrayList;

public class Main
{
   public static void main(String[] args)
   {/*w w w .  j  av a 2  s  .  com*/
      // create a new ArrayList of Strings with an initial capacity of 10
      ArrayList<String> items = new ArrayList<String>(); 

      items.add("red"); // append an item to the list          
      items.add(0, "yellow"); // insert "yellow" at index 0

      // display colors using enhanced for in the display method
      display(items,
         "%nDisplay list contents with enhanced for statement:");

      items.add("green"); // add "green" to the end of the list
      items.add("yellow"); // add "yellow" to the end of the list      
      display(items, "List with two new elements:"); 

   } 

   // display the ArrayList's elements on the console
   public static void display(ArrayList<String> items, String header)
   {
      System.out.print(header); // display header

      // display each element in items
      for (String item : items)
         System.out.printf(" %s", item);

      System.out.println();
   } 
}

Result


Related Tutorials