Java · Course navigation

Java ArrayList and generics

Use a resizable, type-checked sequence.

On this page
Before you start

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

Java
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");
    }
}
Output
[30, 40]

Follow the code

Open the walkthrough to inspect the example one step at a time.

Show guided walkthrough
Guided walkthroughReady
1import java.util.ArrayList;
2import java.util.Arrays;
3class Main {
4 public static void main(String[] args) {
5 ArrayList<Integer> values = new ArrayList<>(Arrays.asList(10, 20, 30));
6 values.remove(1);
7 values.add(40);
8 values.remove(Integer.valueOf(10));
9 System.out.println(values);
10 if (values.size() != 2) throw new AssertionError("size");
11 }
12}

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
Prepared trace of the published program. Some rows group repeated iterations.
Step / lineWhat happensState after stepOutput 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.

Further reading