// This class contains solutions to the sample ArrayList problems discussed // in lecture. It contains some client code that calls the various methods. // translation from array to ArrayList: // String[] => ArrayList // new String[10] => new ArrayList() // a.length => list.size() // a[i] => list.get(i) // a[i] = value; => list.set(i, value); // new operations: // list.remove(i); --remove the ith value // list.add(value); --appends a value // list.add(i, value); --adds at an index // list.clear() --remove all value import java.util.*; public class ArrayListSample { public static void main(String[] args) { ArrayList list = new ArrayList(); list.add("four"); list.add("score"); list.add("seven"); list.add("years"); list.add("what was next?"); list.add("ago"); list.add(2, "and"); list.remove(5); System.out.println("list = " + list); System.out.println(list.indexOf("seven")); stutter(list); System.out.println("after stutter list = " + list); ArrayList list2 = new ArrayList(); list2.add(3); list2.add(8); list2.add(92); list2.add(4); list2.add(2); list2.add(17); list2.add(9); System.out.println("list2 = " + list2); minToFront(list2); System.out.println("after minToFront list2 = " + list2); System.out.println("maxLength returns " + maxLength(list)); removeEvenLength(list); System.out.println("after removeEvenLength list = " + list); } // replaces every value in the list with two of that value public static void stutter(ArrayList list) { for (int i = 0; i < list.size(); i += 2) { String next = list.get(i); list.add(i, next); } } // moves the minimum value to the front of the given list, otherwise // preserving the order of the elements public static void minToFront(ArrayList list) { int min = 0; for (int i = 1; i < list.size(); i++) { if (list.get(i) < list.get(min)) { min = i; } } int oldValue = list.remove(min); list.add(0, oldValue); // could also have been written in one line: // list.add(0, list.remove(min)); } // returns the length of the longest String in the given list public static int maxLength(ArrayList list) { int max = 0; for (int i = 0; i < list.size(); i++) { String s = list.get(i); if (s.length() > max) { max = s.length(); } } return max; } // removes from the list all strings of even length public static void removeEvenLength(ArrayList list) { int i = 0; while (i < list.size()) { String s = list.get(i); if (s.length() % 2 == 0) { list.remove(i); } else { i++; } } } }