Learn Java · lesson 30 of 61 · about 8 minutes
ArrayList
Keep a waiting list for a sold-out showing: use ArrayList for lists that grow and shrink.
What you'll learn
- Create an ArrayList
- Add, get, set and remove items
- Know why it holds Integer, not int
A waiting list
The 20:15 showing is sold out, so the desk keeps a waiting list. Nobody knows how many people will join it, and an array's size is fixed when it's made. An ArrayList grows as names are added and shrinks when someone gives up, so the desk reads names until done, prints the whole list, and takes out the person who leaves with remove.
A growable list
ArrayList<String> names = new ArrayList<>(); (from java.util) is a list that grows as you add.
| Call | Does |
|---|---|
| add(x) | adds to the end |
| get(i) | reads item i |
| set(i, x) | replaces item i |
| remove(i) | removes item i |
| size() | how many items |
| contains(x) | true if x is in the list |
Collections hold objects, so a list of numbers is ArrayList<Integer>. Java converts between int and Integer automatically.
A queue
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> queue = new ArrayList<>();
queue.add("Ada");
queue.add("Bo");
queue.add("Cy");
queue.remove(0);
queue.set(1, "Di");
System.out.println(queue + " " + queue.size() + " " + queue.contains("Bo"));
ArrayList<Integer> scores = new ArrayList<>();
scores.add(70);
scores.add(85);
System.out.println(scores.get(0) + scores.get(1));
}
}Output
[Bo, Di] 2 true
155Tip
Unlike arrays, an ArrayList prints its values directly, in square brackets.
Removing by position or by value
remove comes in two kinds. remove(2) with an int removes the item at index 2. remove("Cy") with an object removes the first item equal to it and returns true, or false if it wasn't there, which is how the desk knows whether the person was on the list. With an ArrayList<Integer>, remove(2) still means index 2: write remove(Integer.valueOf(2)) to remove the value 2.
remove by value tells you if it worked
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> waiting = new ArrayList<>();
waiting.add("Bo");
waiting.add("Cy");
System.out.println(waiting.remove("Cy") + " " + waiting.remove("Zed"));
System.out.println(waiting);
}
}Output
true false
[Bo]Now try it yourself
This lesson is free in Codiqo, with 10 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.