Java ArrayList
Master the dynamic, resizable list that powers real-world Java applications: learn how to create, modify, and traverse an ArrayList.
What Is an ArrayList?
An ArrayList is a class in the java.util package that stores a sequence of object references in a resizable internal array. Unlike a plain array, its length is not fixed at creation time.
Array vs. ArrayList
Why ArrayList Matters
Most real programs don't know their data size in advance. A student roster might start with 20 names and grow to 35 by the second week. An order history could have zero entries today and thousands next month.
Declaring an ArrayList
Essential Methods
| Method | Returns | Description |
|---|---|---|
| add(obj) | boolean | Appends obj to the end |
| add(i, obj) | void | Inserts obj at index i |
| get(i) | E | Returns element at index i |
| set(i, obj) | E | Replaces element at i, returns old |
| remove(i) | E | Removes element at i, shifts left |
| size() | int | Returns number of elements |
How Resizing Works
Array vs. ArrayList: Key Differences
| Feature | Array | ArrayList |
|---|---|---|
| Size | Fixed at creation | Dynamic (grows/shrinks) |
| Syntax to access | arr[i] | list.get(i) |
| Length / size | arr.length | list.size() |
| Holds primitives? | Yes | No (wrapper classes) |
| Insert / remove | Manual shifting | Built-in methods |
| Import needed? | No | java.util.ArrayList |
How to Use an ArrayList
ArrayList<String> list = new ArrayList<>();Example 1: Building a List
Example 2: Removing Elements
Example 3: Traversing an ArrayList
Removing While Traversing
A classic exam pattern: remove all elements matching a condition. Because remove shifts indices, you must either traverse backwards or adjust the index after each removal.
Autoboxing and Unboxing
Java automatically converts between primitive types and their wrapper classes. This lets you use ArrayList<Integer> almost as if it held plain int values.
Common Mistakes
ArrayList<int> instead of ArrayList<Integer>. Type parameters must be reference types, not primitives.Question 1 of 5
What is the output of the following code?ArrayList<String> a = new ArrayList<>();
a.add("X"); a.add("Y"); a.add("Z");
a.add(1, "W");
System.out.println(a.get(2));
Question 2 of 5
Which declaration is valid for an ArrayList that stores integers?
ArrayList<Integer> is the correct syntax. int is a primitive and cannot be used as a type parameter.Question 3 of 5
Given: ArrayList<String> list containing ["A", "B", "C", "D"].
After list.remove(1); what does list.get(1) return?
Question 4 of 5
Which loop correctly prints every element of an ArrayList<String> words?
<= which causes an IndexOutOfBoundsException on the last iteration. Option B starts at 1, skipping index 0. Option C uses array syntax (.length and brackets). Option D is correct: it starts at 0, uses the condition i < words.size(), and calls get(i).Question 5 of 5
When an ArrayList's internal array is full and you call add(), what happens?