How to use ArrayList

Create an ArrayList

Import the class and put the element type in angle brackets. Collections use reference types such as Integer, not primitives such as int.

import java.util.ArrayList;

ArrayList<String> names = new ArrayList<>();

Add and read elements

Use methods rather than array brackets. size() reports the current element count.

names.add("Ada");
names.add("Grace");
System.out.println(names.get(0));
System.out.println(names.size());

Update and remove

set replaces by index, while remove can remove by index or matching object.

names.set(1, "Linus");
names.remove("Ada");
System.out.println(names);

Loop through the list

ArrayList implements Iterable, so it works with an enhanced for loop.

for (String name : names) {
    System.out.println(name);
}