Source of ArrayListDemo.java


  1: //ArrayListDemo.java
  2: //Illustrates the following methods of the ArrayList class:
  3: //add()
  4: //get()
  5: //size()
  6: //remove()
  7: 
  8: import java.util.ArrayList;
  9: import java.util.Scanner;
 10: 
 11: public class ArrayListDemo
 12: {
 13:     public static void main(String[] args)
 14:     {
 15:         ArrayList<String> toDoList = new ArrayList<String>();
 16:         //ArrayList<String> toDoList = new ArrayList<>(); //type inference
 17:         System.out.println("\nEnter items for the list, when prompted.");
 18:         boolean done = false;
 19:         Scanner keyboard = new Scanner(System.in);
 20: 
 21:         while (!done)
 22:         {
 23:             System.out.print("Type an entry: ");
 24:             String entry = keyboard.nextLine();
 25:             toDoList.add(entry);
 26:             System.out.print("More items for the list? (y[n]) ");
 27: 
 28:             String ans = keyboard.nextLine();
 29:             if (!ans.equalsIgnoreCase("y")) done = true;
 30:         }
 31:         System.out.println("\nThe list contains the following items:");
 32:         for (int position = 0; position < toDoList.size(); position++)
 33:             System.out.println(toDoList.get(position));
 34:         System.out.print("Size of the list = ");
 35:         System.out.println(toDoList.size());
 36: 
 37:         //Alternate code for displaying the list
 38:         System.out.println("\nThe list contains the following items:");
 39:         for (String element : toDoList)
 40:             System.out.println(element);
 41:         System.out.print("Size of the list = ");
 42:         System.out.println(toDoList.size());
 43:         System.out.print("Press Enter to continue ... ");
 44:         keyboard.nextLine();
 45: 
 46:         //Now remove items and display again (Oops!)
 47:         for (int position = 0; position < toDoList.size(); position++)
 48:             toDoList.remove(position);
 49:         System.out.println("\nThe list contains the following items:");
 50:         for (String element : toDoList)
 51:             System.out.println(element);
 52:         System.out.print("Size of the list = ");
 53:         System.out.println(toDoList.size());
 54:    }
 55: }