// This class contains solutions to the sample ArrayList problems discussed // in lecture. It contains some client code that calls the various methods. import java.util.*; public class ArrayListSample { public static void main(String[] args) { ArrayList list = new ArrayList(); list.add("hi"); list.add("how"); list.add("are"); list.add("you"); list.add("doing,"); list.add("today?"); System.out.println("list = " + list); stutter(list); System.out.println("after stutter list = " + list); System.out.println("maxLength returns " + maxLength(list)); removeEvenLength(list); System.out.println("after removeEvenLength list = " + list); removeDuplicates(list); System.out.println("after removeDuplicates list = " + list); ArrayList list2 = new ArrayList(); int[] data = {3, 8, 92, 4, 2, 17, 9}; for (int n : data) { list2.add(n); } System.out.println("list2 = " + list2); minToFront(list2); System.out.println("after minToFront list2 = " + list2); } // 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; } // 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)); } // 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++; } } } // 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 s = list.get(i); list.add(i, s); } } // removes duplicate values from the list assuming that the list is in // sorted order to begin with public static void removeDuplicates(ArrayList list) { int index = 0; while (index < list.size() - 1) { if (list.get(index).equals(list.get(index + 1))) { list.remove(index + 1); } else { index++; } } } }