Appending and the full row
After this: Explain capacity, doubling and copying.
On this page · 7 sections · 3 checks
So far our arrays have stayed the same length. Real programs often need to add more as they run: a shopping cart gets new items, and a chat gets new messages. Adding a value at the end of an array is called .
Appending raises a problem. Picture a row of four cells, all full. Where does the fifth value go?
The place right after the row may already be used by something else, so the row cannot stretch. The only option is to create a new, bigger row somewhere else in memory, copy everything into it, and then add the new value. An array that does this for you is called a . Python's list and Java's ArrayList are both dynamic arrays.
Capacity and size
A dynamic array keeps track of two numbers.
- Capacity is how many cells the row has.
- Size is how many of those cells are in use.
A row with capacity 4 and size 2 holds two values and has two spare cells.
| Index | 0 | 1 | 2 | 3 |
|---|---|---|---|---|
| Value | 10 | 20 | (empty) | (empty) |
Appending, step by step
While there is a spare cell, appending takes one write. The new value goes at index size, because that is the first empty cell, and then the size goes up by one. In the row above, 30 goes at index 2, and the size becomes 3.
When size equals capacity, the row is full. Appending now takes three steps. This is called growing the array.
- Create a new row that is twice as big.
- Copy every value into the new row.
- Write the new value.
How much does growing cost?
Each copied value is one write. So the fifth append into a full row of four makes five writes: four copies, plus one for the new value.
The code
Python and Java do all of this for you and keep it hidden. Here is a small version that we write ourselves, so that every step is visible.
class DynamicArray: def __init__(self): self.capacity = 4 self.size = 0 self.cells = [None] * self.capacity # the row of cells; all start empty self.writes = 0 # counts every write, including copies
def append(self, value): if self.size == self.capacity: self._grow() self.cells[self.size] = value self.size += 1 self.writes += 1
def _grow(self): bigger = [None] * (self.capacity * 2) for i in range(self.size): # copy every element across bigger[i] = self.cells[i] self.writes += 1 self.cells = bigger self.capacity *= 2
a = DynamicArray()for v in [10, 20, 30, 40, 50]: a.append(v)print(a.capacity, a.size, a.writes)public class DynamicArray { int capacity = 4; int size = 0; int[] cells = new int[capacity]; // the row of cells; unused cells hold 0 int writes = 0; // counts every write, including copies
void append(int value) { if (size == capacity) grow(); cells[size] = value; size++; writes++; }
private void grow() { int[] bigger = new int[capacity * 2]; for (int i = 0; i < size; i++) { // copy every element across bigger[i] = cells[i]; writes++; } cells = bigger; capacity *= 2; }}Here is how to read it.
capacityandsizeare the two numbers from above, andcellsis the row itself.writesis a counter we added so that we can measure the cost. A real array does not have it.appendchecks whether the row is full. If it is, it grows the row first. Then it writes the value and adds one tosize.- The highlighted lines are the growing step. They create a row twice as big and copy every value across.
Watch it happen
- Append 10The row has 4 cells and none are in use: capacity 4, size 0. There is plenty of room.
- Append 20
- Append 30
- Append 40
- Append 50
- 0·
- 1·
- 2·
- 3·
Run an operation to begin.
The first four appends take one write each. The fifth creates a row of 8, copies 10, 20, 30 and 40, then writes 50. That is nine writes for five appends.
Check yourself
A row has capacity 8 and size 5, so 5 values are in it. Counting from the very first value, which append makes the row copy again?
Starting from an empty row of capacity 4, how many cell writes do five appends make in total (copies included)?
After the five appends, what does the last line print (capacity, size, writes)?
a = DynamicArray()for v in [10, 20, 30, 40, 50]: a.append(v)print(a.capacity, a.size, a.writes)DynamicArray a = new DynamicArray();for (int v : new int[] {10, 20, 30, 40, 50}) a.append(v);System.out.println(a.capacity + " " + a.size + " " + a.writes);Connect
- Define capacity and size, and tell them apart.
- Follow an append into a full row: create a row twice as big, copy every value, then write.
- Count the cell writes a sequence of appends makes.