/** * Demonstration of the use of the ArrayList. Illustrates the use of: * * + ArrayList initialization * + get * + set * + add * + size * * In addition, this program provides a way to experimentally determine how much space can be allocated from the heap. */ import java.util.*; public class ArrayListDemo { // Display the elements of a List public static void display(List x) { for (int i = 0; i < x.size(); i++) System.out.println(x.get(i)); } public static void main(String[] args) { // Create a list, initially empty List myList = new ArrayList(); // Append a few elements to this list myList.add("Bashful"); myList.add("Awful"); myList.add("Jumpy"); myList.add("Happy"); // Display the elements currently stored in myList display(myList); // Now create a list of a few integers List anotherList = new ArrayList(); for (int i = 0; i < 5; i++) anotherList.add(10*i); // ... and display them display(anotherList); // Add 3 to each element in the list for (int i = 0; i < 5; i++) anotherList.set(i, anotherList.get(i) + 3); // ... show the results of the update display(anotherList); // Finally, try to create an ArrayList with a large number of values Scanner in = new Scanner(System.in); System.out.print("How many values should be placed in the ArrayList? "); int howMany = in.nextInt(); System.out.println("Creating ArrayList with " + howMany + " values."); List finalList = new ArrayList(); for (int i = 0; i < howMany; i++) finalList.add(10*i); System.out.println("ArrayList completely populated; size = " + finalList.size()); } }