// Tyler Rigsby, CSE 142 // Contains several examples using ArrayLists // // Translation from array to ArrayList: // String[] ArrayList // new String[n] new ArrayList() // list[i] list.get(i) // list[i] = val list.set(i, val); // list.length list.size() // New operations: // list.add(val) appends val to list // list.remove(i) removes and returns the value at i // list.clear() clears the entire ArrayList import java.util.*; public class ArrayListExamples { public static void main(String[] args) { ArrayList list1 = new ArrayList(); list1.add("it's"); list1.add("friday"); list1.add("friday"); list1.add("gotta"); list1.add("get"); list1.add("down"); list1.add("on"); list1.add("thursday"); list1.set(7, "friday"); System.out.println("list1 = " + list1); System.out.println("max length = " + maxLength(list1)); removeEvenLength(list1); System.out.println("after removeEvenLength = " + list1); echo(list1); System.out.println("after echo = " + list1); ArrayList list2 = new ArrayList(); list2.add(42); list2.add(17); list2.add(37); list2.add(54); System.out.println("list2 = " + list2); minToFront(list2); System.out.println("After minToFront = " + list2); // sorts an ArrayList Collections.sort(list1); } // 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 minIndex = 0; for (int i = 1; i < list.size(); i++) { if (list.get(i) < list.get(minIndex)) { minIndex = i; } } int val = list.remove(minIndex); list.add(0, val); // or, list.add(0, list.remove(minIndex)) } // removes from the list all strings of even length public static void removeEvenLength(ArrayList list) { for (int i = 0; i < list.size(); i++) { String s = list.get(i); if (s.length() % 2 == 0) { list.remove(i); i--; } } } // replaces every value in the list with two of that value public static void echo(ArrayList list) { for (int i = 0; i < list.size(); i += 2) { String s = list.get(i); list.add(i, s); } } }