AP® Computer Science A · Unit 4 · Topic 4.8

ArrayList add, get, set, and size

ArrayList is a resizable list object with methods instead of fixed fields: add appends or inserts, get reads a position, set overwrites a position, and size() reports how many elements are currently there.

A plain array is born with a fixed length and can never change it. An ArrayList is an object that manages a hidden array behind the scenes, so when you add more elements than it currently holds, it quietly builds a bigger array and copies everything over. You never see that resizing happen; you just call add and the list handles it.

Each method has one job. add(x) appends x after the last element, growing the list by one; add(i, x) instead inserts x at index i and shifts everything from i onward one spot to the right. get(i) returns the value sitting at index i without changing anything. set(i, x) overwrites whatever is at index i with x and returns the old value, but it does not change how many elements exist. size() is a method call that returns the current element count, recalculated every time you ask.

This matters because indices still run from 0 to size()-1, exactly like array indices run from 0 to length-1, so all the off-by-one habits from arrays carry straight over. The difference is that size() is a live count you query with parentheses, not a stored number you read off a field. Once you're comfortable with these four methods, the next step is using them inside loops to traverse, search, and shift elements, which is exactly what array algorithms like linear search and insertion do, just written with method calls instead of bracket notation.

Key terms

add(x)
Appends x as the new last element of the list, increasing size by one.
get(i)
Returns the element currently stored at index i without modifying the list.
set(i, x)
Overwrites the element at index i with x and leaves the list's size unchanged.
size()
A method call that returns the current number of elements in the list.
length
A fixed field on an array storing its capacity, set once when the array is created.

Watch it explained

  1. How it worksHow do add, get, set, and size each act on the positions inside a list?
  2. Worked exampleTrace add of a, then b, then set(0, c), and find what get(0) and size return.
  3. Common mistakeWhy isn't size for an ArrayList the same thing as length for an array?
  4. Going furtherWhat happens when you call get on an index equal to the list's size?

Check yourself

Your turn1 of 2
An empty ArrayList has 35 added, then 33 added, then set(0, 47) is called. What does get(0) return afterward?

End of topic.