import java.util.ArrayList; public class ArrayListWithStringGenerics { public static void main(String[] args) { // Generics allows an ArrayList to be created by specifying the type // of element that will be stored in the list; it does limit the // ArrayList to contain only one type of element, but a feature // called autoboxing eliminates the need for the elements to be // cast into their specific type when they are retrieved from the // ArrayList, since the ArrayList will already know what type of // elements it is holding ArrayList list = new ArrayList(); list.add("cat"); // Adds "cat" to ArrayList list.add("dog"); // Adds "dog" to end of ArrayList list.add("zebra"); // Adds "zebra" to end of ArrayList System.out.println("Element #1: " + list.get(0)); System.out.println("Element #2: " + list.get(1)); list.set(0, "fish"); // Changes first element to "fish" System.out.println("Element #1: " + list.get(0)); System.out.println("Element #2: " + list.get(1)); list.add(1, "giraffe"); // Adds "giraffe" at spot #2 list.add("elephant"); // Adds "elephant" to end of ArrayList list.add(1, "dog"); // Adds "dog" at spot #2 // Displays the list contents with a 'for-each' loop for (String animal : list) System.out.print(animal + " "); System.out.println(); list.remove("dog"); // Removes first occurrence of "dog" list.remove(3); // Removes element at spot #4 // Displays the list contents with a 'for' loop for (int spot = 0; spot < list.size(); spot++) System.out.print(list.get(spot) + " "); } }