import java.util.*; /* ArrayList Array ArrayList ------------------------------------------- String[] a ArrayList list a.length list.size() a[i] list.get(i) a[i] = value list.set(i, value) Additional ArrayList Methods ------------------------------------------- list.add(value) // Append the given value at the end of the list list.add(i, value) // Add value at given index and shift -> list.remove(i) // Remove value at given index, shift <- */ public class ArrayListLecture { public static void main(String[] args) { // Husky dubs = new Husky(); // ^ Declaration and initialization is same as other objects ArrayList list = new ArrayList(); // Yo listen up here's a story about a little guy // that lives in a blue world list.add("Yo"); // 0 list.add("listen"); // 1 list.add("up"); // 2 list.add("here's"); // 3 list.add("a"); // 4 list.add("about"); // 5 list.add("a"); // 6 list.add("little"); // 7 list.add("guy"); // 8 list.add("that"); // 9 list.add("lives"); // 10 list.add("in"); // 11 list.add("a"); // 12 list.add("cyan"); // 13 list.add("world"); // 14 System.out.println("Size: " + list.size()); System.out.println(list); list.add(5, "story"); // list.set(13, "blue"); Doesn't work b/c we added before list.set(14, "blue"); System.out.println(list); System.out.println(); ArrayList list2 = new ArrayList(); list2.add(5); list2.add(1); list2.add(3); list2.add(2); repeat(list2); System.out.println(list2); System.out.println(); removeEvenLength(list); System.out.println(list); } // Wrapper classes // ArrayList's type must be a class (not primitive type) // Integer // Double // Boolean // Character // Replaces every value in the given list with two of that value // [5, 1, 2] - > [5, 5, 1, 1, 2, 2] public static void repeat(ArrayList list) { for (int i = 0; i < list.size(); i += 2) { int value = list.get(i); list.add(i + 1, value); } } // Remove all Strings that have an even length from the given ArrayList // [hi, hii] -> [hii] public static void removeEvenLength(ArrayList list) { // Solve by iterating backwards for (int i = list.size() - 1; i >= 0; i--) { String value = list.get(i); if (value.length() % 2 == 0) { // even length list.remove(i); } } /* // Solve by iterating forwards for (int i = 0; i < list.size(); i++) { // Do something with list.get(i) String value = list.get(i); if (value.length() % 2 == 0) { // even length list.remove(i); i--; } } */ } }