12.3 Declaring & Manipulating ArrayList

Key Takeaways

  • ArrayList<E> takes a reference type as its type argument. Use ArrayList<Integer> instead of ArrayList<int>. Diamond syntax belongs in the constructor invocation, as in new 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. set updates both views, and attempts to add or remove an actual element throw UnsupportedOperationException.

  • 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

Last updated: November 2026

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

MethodReturn TypeBehaviorTraps & Exceptions
add(E e)booleanAppends e to end of listAlways returns true for ArrayList
add(int index, E e)voidInserts e at index, shifting rightReturns void (cannot assign); index == size() appends; index > size() throws IndexOutOfBoundsException
get(int index)EReturns element at indexindex < 0 or index >= size() throws IndexOutOfBoundsException
set(int index, E e)EReplaces element at indexReturns the old element; cannot add at index == size() (IndexOutOfBoundsException)
remove(int index)ERemoves element at position indexReturns the removed element; shifts remaining elements left
remove(Object o)booleanRemoves first match using .equalsReturns true if removed, false if not found
size()intNumber of elements currently storedMethod with (), unlike array .length
isEmpty()booleantrue when size() == 0Does not check for null elements
clear()voidRemoves all elements (size() becomes 0)Returns void
contains(Object o)booleantrue if any element equals oUses .equals(), works safely with null
equals(Object o)booleantrue if o is a List with equal elements in the same orderOrder 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 an Object[].
  • String[] strArr = list.toArray(new String[0]); returns a typed String[]. Passing new String[0] is idiomatic because toArray allocates a correctly sized String[] when the passed array is smaller than list.size(). If the passed array is larger, toArray fills indices 0..size()-1 and writes null at index size().

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].

Test Your Knowledge

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);
A

30:[10, 40]

B

20:[10, 30, 40]

C

20:[10, 40]

D

30:[20, 40]

Test Your Knowledge

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);
A

Prints [green, yellow, pink]

B

Throws UnsupportedOperationException at runtime

C

Throws IndexOutOfBoundsException at runtime

D

Compilation fails on Arrays.asList(colors)

Test Your Knowledge

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));
A

true false 10

B

false false 10

C

true true 2

D

true false 2

Sections you finish are checked off in the contents.