Display list contents with counter-controlled loop - Java Language Basics

Java examples for Language Basics:for

Description

Display list contents with counter-controlled loop

Demo Code

import java.util.ArrayList;

public class Main
{
   public static void main(String[] args)
   {// ww  w. ja v a  2 s .c om
      // 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

      // header
      System.out.println("Display list contents with counter-controlled loop:"); 

      // display the colors in the list
      for (int i = 0; i < items.size(); i++)
         System.out.printf(" %s", items.get(i));

   } 

   // 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