Source of ArrayListDemo.java


  1: //ArrayListDemo.java

  3: import java.util.Scanner;

  5: public class ArrayListDemo
  6: {
  7:     public static void main(String[] args)
  8:     {
  9:         int[] numbers = { 3, 2, 84, 18, 91, 6, 19, 12 };

 11:         // Initialize a new ArrayList and add numbers
 12:         ArrayList myList = new ArrayList();
 13:         for (int number : numbers)
 14:             myList.append(number);

 16:         // Show the array before the operation
 17:         System.out.println("-- Array before operation --");
 18:         myList.printInfo();
 19:         System.out.println();
 20:         myList.print();
 21:         System.out.println();

 23:         // Read an instruction
 24:         Scanner scanner = new Scanner(System.in);
 25:         String instructionLine = scanner.nextLine();
 26:         String[] instruction = instructionLine.split(" ");
 27:         String method = instruction[0];

 29:         int item, index;
 30:         if (method.equals("append"))
 31:         {
 32:             item = Integer.parseInt(instruction[1]);
 33:             myList.append(item);
 34:         }
 35:         else if (method.equals("insertAfter"))
 36:         {
 37:             index = Integer.parseInt(instruction[1]);
 38:             item = Integer.parseInt(instruction[2]);
 39:             myList.insertAfter(index, item);
 40:         }
 41:         else if (method.equals("prepend"))
 42:         {
 43:             item = Integer.parseInt(instruction[1]);
 44:             myList.prepend(item);
 45:         }
 46:         else if (method.equals("removeAt"))
 47:         {
 48:             index = Integer.parseInt(instruction[1]);
 49:             myList.removeAt(index);
 50:         }
 51:         else if (method.equals("search"))
 52:         {
 53:             item = Integer.parseInt(instruction[1]);
 54:             System.out.println("Search result: " + myList.search(item));
 55:         }
 56:         else
 57:         {
 58:             System.out.println("Unknown method: " + method);
 59:         }

 61:         System.out.println();
 62:         System.out.println("-- Array after operation --");
 63:         myList.printInfo();
 64:         System.out.println();
 65:         myList.print();
 66:         System.out.println();
 67:     }
 68: }