12.3 Declaring & Manipulating ArrayList
Key Takeaways
ArrayList<E>takes a reference type as its type argument. UseArrayList<Integer>instead ofArrayList<int>. Diamond syntax belongs in the constructor invocation, as innew ArrayList<>().add(E) appends and returns boolean, add(int, E) inserts and returns void, and set(int, E) replaces an existing element and returns the old element without growing the list
On
ArrayList<Integer>,list.remove(1)removes index 1.list.remove(Integer.valueOf(1))removes the first equal element if present.Arrays.asList(array)returns a fixed-size list backed by the array.setupdates both views, and attempts to add or remove an actual element throwUnsupportedOperationException.ArrayList.equals(Object) returns true if another List contains equal elements in the exact same order, and Collections.sort(list) sorts elements in place by natural Comparable order
Imports, Declarations, and the Diamond Operator
java.util.ArrayList is a resizable array implementation of the java.util.List interface. Neither type is in java.lang. To use their simple names in another package, import them individually or use import java.util.*;. You can also use their fully qualified names.
Valid and Invalid Declarations
import java.util.ArrayList;
import java.util.List;
List<String> names = new ArrayList<>(); // Diamond operator (Java 7+)
ArrayList<String> exact = new ArrayList<String>(); // Explicit on both sides
ArrayList<String> sized = new ArrayList<>(10); // Initial capacity 10, size() == 0
ArrayList raw = new ArrayList(); // Raw type: holds Object
// DOES NOT COMPILE: diamond <> cannot appear on the left side
// ArrayList<> bad = new ArrayList<String>();
// DOES NOT COMPILE: primitives are illegal as generic type arguments
// ArrayList<int> nums = new ArrayList<>();
A raw ArrayList stores elements as Object, allowing mixed types ("hi" and 42) at the cost of losing compile-time type safety and requiring explicit casts on retrieval. Generic ArrayList<Integer> enforces type checks at compile time and relies on autoboxing (int to Integer) and unboxing (Integer to int).
Warning
Adding null to an ArrayList<Integer> succeeds because null is a valid reference. However, unboxing that null into a primitive int (int x = list.get(0);) throws NullPointerException at runtime.
Core ArrayList Methods
| Method | Return Type | Behavior | Traps & Exceptions |
|---|---|---|---|
add(E e) | boolean | Appends e to end of list | Always returns true for ArrayList |
add(int index, E e) | void | Inserts e at index, shifting right | Returns void (cannot assign); index == size() appends; index > size() throws IndexOutOfBoundsException |
get(int index) | E | Returns element at index | index < 0 or index >= size() throws IndexOutOfBoundsException |
set(int index, E e) | E | Replaces element at index | Returns the old element; cannot add at index == size() (IndexOutOfBoundsException) |
remove(int index) | E | Removes element at position index | Returns the removed element; shifts remaining elements left |
remove(Object o) | boolean | Removes first match using .equals | Returns true if removed, false if not found |
size() | int | Number of elements currently stored | Method with (), unlike array .length |
isEmpty() | boolean | true when size() == 0 | Does not check for null elements |
clear() | void | Removes all elements (size() becomes 0) | Returns void |
contains(Object o) | boolean | true if any element equals o | Uses .equals(), works safely with null |
equals(Object o) | boolean | true if o is a List with equal elements in the same order | Order matters; compares across List implementations |
The ArrayList<Integer> remove Overload Trap
Because List overloads remove(int index) and remove(Object o), calling remove on an ArrayList<Integer> with an int literal always selects remove(int index) (exact primitive match beats autoboxing):
List<Integer> numbers = new ArrayList<>();
numbers.add(1); // [1]
numbers.add(2); // [1, 2]
numbers.add(3); // [1, 2, 3]
numbers.remove(1); // Removes index 1 (value 2) -> [1, 3]
numbers.remove(Integer.valueOf(1)); // Removes object 1 -> [3]
System.out.println(numbers); // Prints: [3]
Watch closely when numbers.remove(5) is called on [1, 3]: it does not return false—it tries to remove index 5 and throws IndexOutOfBoundsException!
Converting Between Arrays and Lists
Arrays.asList(...): Fixed-Size Backed View
Arrays.asList(array) (or Arrays.asList("a", "b")) returns a fixed-size List backed by the underlying array:
String[] arr = {"hawk", "robin"};
List<String> list = Arrays.asList(arr);
list.set(1, "test"); // Updates BOTH list and arr[1]
arr[0] = "new"; // Updates BOTH arr[0] and list.get(0)
System.out.println(Arrays.toString(arr)); // [new, test]
System.out.println(list); // [new, test]
// list.add("crow"); // Throws UnsupportedOperationException
// list.remove(0); // Throws UnsupportedOperationException
If you need a genuinely resizable ArrayList copied from an array, pass the fixed view to the ArrayList constructor:
List<String> resizable = new ArrayList<>(Arrays.asList(arr));
resizable.add("crow"); // Works! Does NOT modify arr
toArray(): List to Array
Object[] objArr = list.toArray();returns anObject[].String[] strArr = list.toArray(new String[0]);returns a typedString[]. Passingnew String[0]is idiomatic becausetoArrayallocates a correctly sizedString[]when the passed array is smaller thanlist.size(). If the passed array is larger,toArrayfills indices0..size()-1and writesnullat indexsize().
Sorting, Copying, and Safe Removal During Iteration
Collections.sort(list) sorts a List in place using natural ordering (Comparable). Watch String sorting carefully—UTF-16 code units put these ASCII digits ('0'–'9', 48–57) before uppercase letters ('A'–'Z', 65–90), which come before lowercase letters ('a'–'z', 97–122). By contrast, List<Integer> sorts numerically because Integer.compareTo compares numeric values:
List<String> items = new ArrayList<>(Arrays.asList("2", "10", "B", "a"));
Collections.sort(items);
System.out.println(items); // [10, 2, B, a]
List<Integer> nums = new ArrayList<>(Arrays.asList(2, 10, -5));
Collections.sort(nums);
System.out.println(nums); // [-5, 2, 10]
When copying an ArrayList with new ArrayList<>(existingList), the new list receives a shallow copy of the element references: adding or removing elements in the copy does not resize existingList, though mutating a mutable element (such as a StringBuilder) inside one list is visible through the other.
Avoiding ConcurrentModificationException
Directly removing elements from an ArrayList during enhanced-for iteration can cause ConcurrentModificationException. Fail-fast detection is best effort. In Java SE 8 you can call removeIf outside the loop to remove every element matching a predicate:
// Unsafe during iteration: may throw ConcurrentModificationException
// for (String s : items) { if (s.length() > 1) items.remove(s); }
// Safe in Java 8:
items.removeIf(s -> s.length() > 1);
System.out.println(items); // [2, B, a]
ArrayList.equals(Object) checks element-by-element equality in order: [2, B, a] does not equal [B, 2, a].
What is the output of the following code?
List<Integer> list = new ArrayList<>();
list.add(10);
list.add(20);
list.add(1, 30);
int old = list.set(2, 40);
list.remove(1);
System.out.println(old + ":" + list);
30:[10, 40]
20:[10, 30, 40]
20:[10, 40]
30:[20, 40]
What happens when the following code is executed?
String[] colors = {"red", "blue"};
List<String> list = Arrays.asList(colors);
list.set(0, "green");
colors[1] = "yellow";
list.add("pink");
System.out.println(list);
Prints [green, yellow, pink]
Throws UnsupportedOperationException at runtime
Throws IndexOutOfBoundsException at runtime
Compilation fails on Arrays.asList(colors)
What is the result of running this snippet?
List<String> a = new ArrayList<>();
a.add("2");
a.add("10");
a.add("A");
List<String> b = Arrays.asList("2", "10", "A");
System.out.print(a.equals(b) + " ");
Collections.sort(a);
System.out.print(a.equals(b) + " " + a.get(0));
true false 10
false false 10
true true 2
true false 2
Sections you finish are checked off in the contents.