ArrayList Methods
| English | Chinese | Pinyin |
|---|---|---|
| ArrayList | 动态数组 | dòng tài shù zǔ |
A resizable list
- An
ArrayList动态数组 is a resizable list of objects — it grows and shrinks as needed. - Declare with a type parameter:
ArrayList<String> names = new ArrayList<String>(); - Unlike an array, you don't fix a size — it adjusts automatically.
- Its methods (not
[]and.length) are how you use it.
add and get
add(x)appendsxto the end of the list.add(i, x)insertsxat indexi, shifting later elements right.get(i)returns the element at indexi(indexed from0, like arrays).size()returns how many elements the list holds.
set and remove
set(i, x)replaces the element at indexiwithx(returns the old one).remove(i)deletes the element at indexi, shifting later elements left.- After a
remove, the list is one shorter and indices shift. size()reflects the new count after any add or remove.
Array vs. ArrayList syntax
- Array:
a[i],a.length, fixed size. ArrayList:list.get(i),list.size(), resizable. - No
[]on an ArrayList; no.get()/.add()on an array. - An ArrayList holds objects (use
Integer, notint). - Pick an array for a fixed count, an ArrayList when it changes.
ArrayList uses methods, not array syntax: list.get(i) and list.size(), never list[i] or list.length. And a remove(i) shifts every later element left and shrinks size() by one — so looping forward and removing as you go skips elements unless you adjust the index. Removing while iterating is a classic bug.
Using ArrayList methods:
ArrayList<String> a = new ArrayList<String>();a.add("cat"); a.add("dog");→ size2,a.get(0)is"cat".a.remove(0);→"cat"gone,"dog"shifts to index0, size1.
An ArrayList<Type> is a resizable list of objects, used through methods: add, get(i), set(i, x), remove(i), and size() — never [] or .length. add(i,x) shifts elements right; remove(i) shifts them left and shrinks size(). Use it when the count changes.
add, get, and remove
After remove(0), dog shifts to index 0 and size drops to 1.
How do you get the number of elements in an ArrayList list?
ArrayList uses size(); arrays use .length.
How do you access the element at index 2 of an ArrayList list?
ArrayList uses get(i), not [i].
After a.remove(0) on {cat, dog}, what is a.get(0)?
remove(0) deletes cat; dog shifts to index 0.
You can access an ArrayList element with square brackets, like list[0].
ArrayList uses methods (get/set), not [] syntax.
add(x) with one argument adds x...
add(x) appends; add(i, x) inserts at index i.