Arrays and ArrayList

Lesson 3 of 20

Fill an ArrayList until it bursts and watch it grow and copy — then compare fixed arrays against resizable lists.

The big picture

Arrays vs ArrayList

Two ways to hold a row of values in Java: the raw array you size once, and the ArrayList that grows for you — each with a different bill.

The raw array

int[] a = new int[5]; — fixed length forever, exposed via a.length. Contiguous memory makes a[i] a single jump: O(1).

The ArrayList

From java.util.ArrayList: wraps an array it secretly doubles when full. size() tells the truth; capacity stays hidden.

Amortized add

Most adds are one O(1) write. Every so often the list grows and copies everything — spread across all adds, still O(1) average.

The costly ends

add(0, x) or remove(0) shift every element. Ends are cheap; middles and fronts are not.

2-D arrays

int[][] grid = new int[3][4]; — grid.length is the row count, grid[0].length the columns. Rows can even have different lengths.