Skip to the workspace
Pebellslearn by building
Collections  ›  Lesson

Array vs ArrayList

Array vs ArrayList 14 minAn array has a fixed length set at creation, while an ArrayList is a generic, resizable list that grows and shrinks as elements are added and removed.

java / Array vs ArrayList

Explore each scene at your own pace.

01 · The rule

The rule

Array vs ArrayList

An array has a fixed length set at creation, while an ArrayList is a generic, resizable list that grows and shrinks as elements are added and removed.

Choose fixed storage or a growable list and inspect their access costs.

A Brew Bar order starts with one drink, then the customer adds a muffin, then removes it, then adds two more coffees. An array's length is fixed the moment it is created, so it copes badly. ArrayList is the everyday answer: an ordered list that grows and shrinks as you go.

The rule

Fixed size, use an array; growing size, use an ArrayList.

List<String> items = new ArrayList<>();
items.add("Latte");                 // [Latte]
items.add("Muffin");                // [Latte, Muffin]
items.add(0, "Mocha");              // [Mocha, Latte, Muffin]
items.set(2, "Scone");              // [Mocha, Latte, Scone]
items.remove("Latte");              // [Mocha, Scone]
System.out.println(items.get(0));   // Mocha
System.out.println(items.size());   // 2
System.out.println(items);          // [Mocha, Scone]

Side by side:

Array ArrayList
Size fixed at creation grows and shrinks
Read arr[i] list.get(i)
Write arr[i] = x list.set(i, x)
Length arr.length list.size()
Holds primitives yes, int[] no, uses wrappers: List<Integer>
Prints nicely no yes

The <String> part is a generic type argument: it tells the compiler what the list holds. Adding a number to a List<String> is then a compile error rather than a surprise later. The <> on the right, called the diamond, lets Java repeat the type for you. Generics only accept reference types, so you write List<Integer>, not List<int>. Java converts between int and Integer automatically (autoboxing).

Declaring the variable as the interface List rather than ArrayList keeps your code flexible, since it only relies on what every list can do.

Two common catches:

  • remove has two versions. On a List<Integer>, remove(1) removes the element at index 1, not the value 1. To remove a value, pass an object: remove(Integer.valueOf(1)).
  • List.of(...) is unchangeable. It is great for fixed data, but calling add on it throws an UnsupportedOperationException. Wrap it, new ArrayList<>(List.of(...)), when you need to edit.
Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.