ArrayList
ArrayList is the default resizable list in Java. It keeps elements in an array behind the scenes, so reading by position is instant, while inserting in the middle has to shift everything after it.
Detailed Explanation
A Java array has a fixed length. Once you write new String[10] you have ten slots forever. Growing it means allocating a bigger array and copying. ArrayList does that bookkeeping for you and exposes a list that appears to grow on demand.
Internally there is one Object[] and an int size. size is how many slots hold real elements; the array's length is the capacity. When you add past the capacity, ArrayList allocates a new array about 1.5 times as long (oldCapacity + (oldCapacity >> 1)), copies the old contents with System.arraycopy, and drops the old array. The default capacity is 10, and it is allocated lazily on the first add, so an empty ArrayList costs almost nothing.
That design explains every cost:
| Operation | Cost | Why |
|---|---|---|
get(i), set(i, e) | O(1) | one array index |
add(e) at the end | amortised O(1) | occasional copy, spread over many adds |
add(i, e), remove(i) | O(n) | shifts every later element |
contains(e), indexOf(e) | O(n) | linear scan calling equals |
remove(Object) | O(n) | scan, then shift |
Ordering is insertion order and nothing else, so iteration yields elements in the order you added them. null is a legal element, as many times as you like. ArrayList is not thread-safe: two threads adding at once can lose an element or corrupt size. Its iterators are fail-fast, which means they throw ConcurrentModificationException when the list is structurally changed during iteration through anything other than the iterator itself.
When do you reach for it? Almost always, when you want a list. You are reading lines from a log file and keeping them in order; you are building up results before returning them; you are holding the rows of a query. The access pattern that suits ArrayList is "append at the end, read by index, iterate front to back", which covers most code.
The costs worth knowing. Insertion and deletion near the front are linear, so a queue built on ArrayList with remove(0) is quadratic. Growth copies, so pre-sizing with new ArrayList<>(expectedSize) avoids repeated array copies when you know the size roughly. Memory is one reference per slot plus up to a third wasted headroom after a grow; trimToSize() reclaims it. And a list of numbers stores boxed Integer objects, not ints, which costs roughly four times the memory of an int[] and adds a pointer dereference per read.
Vector is the older synchronised equivalent, kept only for backwards compatibility. It locks on every single method, which buys you nothing because a lock per call does not make a sequence of calls atomic. Use ArrayList, and if you need thread safety use CopyOnWriteArrayList or guard the list yourself.
Code Examples
import java.util.ArrayList;
import java.util.List;
public class AccessLog {
public static void main(String[] args) {
// Pre-size when you roughly know the count: this avoids repeated copies.
List<String> lines = new ArrayList<>(1000);
lines.add("GET /home 200");
lines.add("GET /cart 500");
lines.add("POST /pay 200");
System.out.println(lines.get(1)); // prints: GET /cart 500
System.out.println(lines.size()); // prints: 3
// remove(int) shifts every later element one slot left, so it is O(n).
lines.remove(0);
System.out.println(lines.get(0)); // prints: GET /cart 500
// removeIf is the correct way to filter in place. A for-each with
// remove() inside would throw ConcurrentModificationException.
lines.removeIf(line -> line.endsWith("200"));
System.out.println(lines); // prints: [GET /cart 500]
}
}import java.util.ArrayList;
import java.util.List;
public class BoxingCost {
public static void main(String[] args) {
// A List cannot hold primitives. Every int becomes an Integer object.
List<Integer> boxed = new ArrayList<>();
for (int i = 0; i < 5; i++) {
boxed.add(i); // autoboxing: int -> Integer
}
int[] raw = new int[5]; // no objects, no pointer chasing
for (int i = 0; i < 5; i++) {
raw[i] = i;
}
var total = 0;
for (int value : boxed) { // unboxing on every iteration
total += value;
}
System.out.println(total); // prints: 10
System.out.println(raw.length); // prints: 5
}
}Common Gotchas
`remove(int)` and `remove(Object)` are different methods
on a `List<Integer>`, `list.remove(1)` deletes the element at index 1, not the value 1. Write `list.remove(Integer.valueOf(1))` when you mean the value. This silently deletes the wrong element, or throws `IndexOutOfBoundsException`.
Structural change during a for-each throws
adding or removing inside an enhanced `for` loop raises `ConcurrentModificationException`. Use `removeIf`, or an explicit `Iterator` and its `remove()`.
`subList` is a live view, not a copy
writes through it change the parent list, and structurally modifying the parent makes the sublist throw on its next use. Copy with `new ArrayList<>(list.subList(a, b))` when you want independence.
Capacity is not size
`new ArrayList<>(100)` has size 0, so `get(0)` throws. The argument reserves room; it does not create elements.