Java ArrayList and generics

Use a resizable, type-checked sequence.

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]

Explanation

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.

Explore the dry run
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]

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