Unit 4 Day 20 Arraylist vs. Array
Share
Practice Question
Statement I: Arrays can store primitive types directly;
ArrayLists can only store object references.
Statement II: Arrays have a fixed size determined at creation;
ArrayLists can grow and shrink dynamically.
Statement III: Accessing an element by index is O(1) for arrays
but O(n) for ArrayLists.
Step-by-Step Trace
// Statement I: TRUE
int[] nums = new int[5]; // stores primitives directly
ArrayList<Integer> list; // must use Integer wrapper
// ArrayList is ILLEGAL - cannot use primitive types
// Statement II: TRUE
int[] arr = new int[10]; // fixed at 10 forever
ArrayList<String> list = new ArrayList<>();
list.add("A"); list.add("B"); // grows as needed
list.remove(0); // shrinks as needed
// Statement III: FALSE
// Both arrays and ArrayLists have O(1) index access!
// arr[5] and list.get(5) are both constant time
// ArrayList is backed by an array internally
Key Concept
Arrays: Fixed size, can hold primitives or objects, use [] syntax, length is a field.
ArrayLists: Dynamic size, objects only (use wrappers for primitives), use methods like get()/set()/add()/remove(), size() is a method.
Performance: Both have O(1) random access by index. ArrayList add() is O(1) amortized at the end, but O(n) when inserting in the middle due to shifting.
Common Mistakes
ArrayList is backed by an array internally, so list.get(i) is O(1) constant time, just like arr[i]. Only add(index, obj) and remove(index) are O(n) because they require shifting.
Both I and II are true. Arrays truly are fixed size (you must create a new array to "resize"), and ArrayLists truly cannot hold primitives directly.
For the AP exam, remember: ArrayList get() is O(1), but add/remove in the middle is O(n) due to shifting. Arrays are faster for primitives (no autoboxing overhead).
Want More Practice?
Master AP CSA with guided practice and expert help
Schedule 1-on-1 Tutoring Practice FRQs