Grade 11 Computer Science · A collection that grows

A structure that grows over one that does not

How it works, and why it is worth knowing.

A list that grows, over an array that cannot

You learned that an array cannot grow by even one cell, and yet you can add items to a list without end. There is no magic here and no structure new from the ground up — there is a trick. And most of the time you will not feel it, except in one place where it can turn innocent code very slow.

An array does not grow, and clearly something that does is needed. The solution is not a structure new from the ground up but a clever wrapper: a structure holding inside it an array larger than needed, remembering how many cells are really in use, and replacing the array when the room runs out. This is a perfect example of the abstraction you learned — a name, a promise, and hidden details.

The structure reserves more room than is in use, and replaces when it runs out.
import java.util.ArrayList;

ArrayList<String> names = new ArrayList<>();
names.add("dana");
names.add("omar");

System.out.println(names.size());    // 2 — what is in use
System.out.println(names.get(0));    // dana
// the capacity is never shown, and never needs to be

Why it is worth knowing what hides inside

Ostensibly this violates the abstraction: if the details are hidden, why learn them? The answer is that this abstraction leaks in exactly one place — in performance. Adding at the end is cheap, but adding or deleting in the middle requires shifting everything after, exactly as in an array. Whoever does not know this writes a loop deleting from the head at every turn, and gets quadratic code without understanding why. This is exactly the case you were warned of in grade nine: a leaky abstraction worth knowing about.

The termWhat it isVisible
SizeHow many items are insideYes
CapacityHow many cells were reservedNo

Example 1 — why the copying is not dear on average

  1. It happens only when the room runs out.
  2. And then the capacity grows substantially.
  3. So it is rare relative to the additions.

Example 2 — why adding in the middle is dear

  1. Everything after must be shifted.
  2. Exactly as in an array.
  3. And the abstraction does not hide the cost.
Move n into the thousands: the total copies grow, but the copies per addition barely move. That is why adding at the end is cheap.