Video in progress
ArrayList.add is called amortized O(1). What does amortized mean?
Some calls are expensive (when the internal array is full, copying to a bigger array is O(n)), but they are rare. Averaged over many calls, the cost per add comes out constant.
📖 Answer
Inside ArrayList there is an array. When it fills up, a new array about 1.5 times larger is allocated and all elements are copied.
Let's count. Since the capacity keeps growing, the copies involve n, n/1.5, n/1.5², ... elements: a geometric series whose sum is a few times n. So for n add calls the total work is O(n), which is O(1) on average per call.
This isn't the same as the "average case". Amortization is a guarantee about the sequence, not about luck: whatever the input is, n operations cost O(n) in total.
What you need in practice:
- if the number of elements is known in advance,
new ArrayList<>(n)means there are no copies at all; - where low latency is required, even a single "expensive"
addcan be noticeable: copying an array of a million elements takes milliseconds.
The same idea applies to HashMap rehashing and StringBuilder growth.
Sign up to mark studied questions and save your progress.