All lessons

ArrayLists

8 min · Java

Java's resizable lists — add, remove, and reach items by index.

Java · ArrayLists0/5 cleared

Enemy 1 of 5

Java does have a plain array type, but its size is fixed forever once created — useful in some situations, but inconvenient the moment you don't know in advance how many items you'll end up with. An ArrayList solves that: it holds many values in order, just like an array, but can grow or shrink as your program runs.

To use one, you first import java.util.ArrayList (Java organizes its built-in tools into packages, and import brings a specific one into your file), then new ArrayList<>() creates an empty list. The <String> part is called a generic type parameter — it tells Java exactly what kind of values this particular ArrayList is allowed to hold, so an ArrayList<String> can never accidentally end up holding a number.

.add() appends a new value to the end. .get(index) reads the value at a given position, counting from 0 — the same zero-based indexing you'll see in every language's collections, so the first item is index 0, not 1.

You
Goblin Glitch

Loading editor...

Ln 1, Col 1Spaces: 4
Sign up to fightTarget output: apple