Java ArrayList and generics
Use a resizable, type-checked sequence.
On this page
Arrays, objects, and imports.
- Use a resizable, type-checked sequence.
- Predict the sample output and explain the state changes.
- Complete the practice task and check the boundary cases.
The concept
ArrayList<Integer> stores references to Integer values and grows as elements are added. Java boxes int values into Integer objects for this generic collection.
remove has overloads: remove(int) removes by index, while remove(Object) removes a matching value. Explicit Integer.valueOf chooses the value overload.
Code example
import java.util.ArrayList;
import java.util.Arrays;
class Main {
public static void main(String[] args) {
ArrayList<Integer> values = new ArrayList<>(Arrays.asList(10, 20, 30));
values.remove(1);
values.add(40);
values.remove(Integer.valueOf(10));
System.out.println(values);
if (values.size() != 2) throw new AssertionError("size");
}
}[30, 40]
Follow the code
Open the walkthrough to inspect the example one step at a time.
Show guided walkthrough
import java.util.ArrayList;import java.util.Arrays;class Main { public static void main(String[] args) { ArrayList<Integer> values = new ArrayList<>(Arrays.asList(10, 20, 30)); values.remove(1); values.add(40); values.remove(Integer.valueOf(10)); System.out.println(values); if (values.size() != 2) throw new AssertionError("size"); }}Follow the example
Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.
View the complete dry-run table
| Step / line | What happens | State after step | Output so far |
|---|---|---|---|
| Make a mutable resizable copy. | values = [10, 20, 30] | — | |
| Remove the item at index 1. | values = [10, 30] | — | |
| Append 40. | values = [10, 30, 40] | — | |
| Remove value 10, not index 10. | values = [30, 40] | — | |
| Print the list. | values = [30, 40] | [30, 40] |
Behind the scenes
How Java processes this code
The Java compiler produces bytecode. The JVM loads the class and invokes its main method.
Cost and common mistakes
O(1) indexed access, amortized O(1) append, O(n) removal/search/shift in general. O(n) storage.
- Generics use wrapper types such as Integer, not primitive int as a type parameter.
- Index removal and value removal have different meanings.
Try it yourself
Call values.remove(Integer.valueOf(99)).
Reveal answer and reasoning
It returns false and leaves the list unchanged because 99 is absent.