import java.util.Arrays; import java.util.ArrayList; /**** * * This class illustrates some of the basic ideas for arrays and ArrayLists. * In 102, you'll primarily be using ArrayLists instead of arrays, but use of * arrays may be convenient in some cases. NOTE: In labs and programming * assignments where it says you must use an ArrayList, using an plain array * will not do. */ public class ArraysAndArrayLists { public static void main(String[] args) { // Allocate a 10-element array. int a[] = new int[10]; // Allocate a flexible-size ArrayList. ArrayList al = new ArrayList(); // Assign the values 0 through 90 to both the array and ArrayList. for (int i = 0; i < 10; i++) { a[i] = i * 10; al.add(i * 10); } // Print out the elements of the array, using a standard for loop. for (int i = 0; i < 10; i++) { System.out.print(a[i] + " "); } System.out.println(); // Print out the elements of the ArrayList, using standard for loop. for (int i = 0; i < 10; i++) { System.out.print(al.get(i) + " "); } System.out.println(); // Increment each element of the array and ArrayList by 1. for (int i = 0; i < 10; i++) { a[i]++; al.set(i, al.get(i) + 1); } // // Print out the elements of the array and ArrayList in different ways. // // Use the Arrays.toString library method on the array. System.out.println(Arrays.toString(a)); // Use (indirectly) the ArrayList.toString method. System.out.println(al); // Use the specialized form of for loop on ArrayLists. for (int i : al) { System.out.print(i + " "); } System.out.println(); // Try to print the array directly; what's going on here? System.out.println(a + " -- Say what?"); } }