Command Palette

Search for a command to run...

Back to the lesson: Topic 9.2 — ArrayList Inside Out
Core Java · Example 1 of 4

Watch the capacity grow by 1.5x

Under 3 copies per add on average: that's what amortised O(1) means in practice.

ArrayList is a growable array: an Object[] plus a size counter. Reading by index is O(1), adding at the end is amortised O(1) because the array grows by 1.5x when full, and inserting or removing in the middle is O(n) because System.arraycopy shifts every later element.

Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write static List<Integer> capacities(int adds) that returns the capacity sequence an ArrayList goes through (starting from 10 at the first add) while adding adds elements. Print the result for 100 adds.

02

Given List<String> words = new ArrayList<>(List.of("a", "bb", "ccc", "dd", "e")), remove every word of length 2 in a single O(n) pass without removeIf, by compacting in place with a write index, then trimming the tail.

03

Show that list.subList(1, 3).clear() removes elements from the original list. Start with [0, 1, 2, 3, 4] and print the list after the call.

Explain it without notes

01

Describe how ArrayList.add works, including what happens when the array is full.

02

Why is appending to an ArrayList amortised O(1) when a single add can be O(n)?

03

What is the difference between capacity and size, and how do ensureCapacity and trimToSize relate to them?

04

Why is ArrayList usually faster than LinkedList even for some insert-heavy workloads?

05

What is the cost of add(0, e), remove(0), contains(e) and get(i) on an ArrayList of n elements?

Watch the capacity grow by 1.5x
Sign in to run this example in your browser.

Expected output

first capacities: 10 -> 15 -> 22 -> 33 -> 49 -> 73 -> 109 -> 163 -> 244
grows for 1000 adds: 12
final capacity: 1234
references copied in total: 2456
copies per add: 2.456