Sub topic 3
Ordered Sequences with List and ArrayList
A list is a collection that keeps its elements in a fixed order. Each element sits at a numbered position, and you can read or change it by that number. Lists also allow duplicates, meaning the same value can appear more than once.
In Java, List is an interface: a set of methods that any list must provide. ArrayList is a class that implements that interface. It is the list you will use most often. This chapter shows you how to create an ArrayList, add elements, read them, change them, and remove them. It also explains what happens inside the list.
What makes a List different
The previous chapters introduced the Collection interface and generic types such as List<String>. A List is a Collection with three extra promises:
- Order is kept. Elements stay in the order you put them in, unless you move them.
- Duplicates are allowed. You can add
"Ana"twice and both copies stay. - Positions have numbers. Each element has an index, a whole number that gives its position. The first index is
0, not1.
The table compares a list with a plain Java array, which you already know.
| Feature | Array (`String[]`) | `ArrayList<String>` |
|---|---|---|
| Size | Fixed when created | Grows and shrinks as needed |
| Read element | `arr[2]` | `list.get(2)` |
| Change element | `arr[2] = "x"` | `list.set(2, "x")` |
| Add at end | Not possible | `list.add("x")` |
| Remove element | Not possible | `list.remove(2)` |
| Length | `arr.length` | `list.size()` |
| Print contents | Prints a memory code | Prints `[a, b, c]` |
Creating a list and adding elements
Here is a first example. It creates a list, adds names, reads one back, and replaces one.
import java.util.ArrayList;
import java.util.List;
public class ListDemo {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
names.add("Ana");
names.add("Ben");
names.add("Ana");
System.out.println(names); // [Ana, Ben, Ana]
System.out.println(names.get(1)); // Ben
names.set(1, "Cara");
System.out.println(names); // [Ana, Cara, Ana]
System.out.println(names.size()); // 3
}
}Look at each step:
new ArrayList<>()makes an empty list. Its size is0.add("Ana")puts"Ana"at the end. Eachaddmakes the list one longer.- The second
"Ana"is kept, because lists allow duplicates. get(1)returns the element at index 1. That is"Ben", the second element.set(1, "Cara")replaces the element at index 1. The size does not change.size()returns how many elements the list holds.
Picturing indexes
It helps to picture a list as a row of numbered boxes.
The last valid index is always size() - 1. A list of 3 elements has indexes 0, 1, and 2. Index 3 does not exist.
Inserting, searching, and removing
You can do more than add elements at the end. The next program inserts an element in the middle, searches the list, and removes elements.
import java.util.ArrayList;
import java.util.List;
public class ListOpsDemo {
public static void main(String[] args) {
List<String> tasks = new ArrayList<>();
tasks.add("wash");
tasks.add("dry");
tasks.add(1, "rinse"); // insert at index 1
System.out.println(tasks); // [wash, rinse, dry]
tasks.add("rinse");
System.out.println(tasks); // [wash, rinse, dry, rinse]
System.out.println(tasks.contains("dry")); // true
System.out.println(tasks.indexOf("rinse")); // 1
System.out.println(tasks.lastIndexOf("rinse")); // 3
System.out.println(tasks.indexOf("fold")); // -1
String removed = tasks.remove(0); // remove by index
System.out.println(removed); // wash
System.out.println(tasks); // [rinse, dry, rinse]
boolean found = tasks.remove("rinse"); // remove first match by value
System.out.println(found); // true
System.out.println(tasks); // [dry, rinse]
tasks.clear();
System.out.println(tasks.isEmpty()); // true
}
}Here is what each method does:
| Method | What it does | Returns |
|---|---|---|
| `add(e)` | Adds `e` at the end | `true` |
| `add(i, e)` | Inserts `e` at index `i`, shifting later elements right | nothing |
| `get(i)` | Reads the element at index `i` | the element |
| `set(i, e)` | Replaces the element at index `i` | the old element |
| `remove(i)` | Removes the element at index `i`, shifting later elements left | the removed element |
| `remove(e)` | Removes the first element equal to `e` | `true` if found |
| `contains(e)` | Checks whether `e` is in the list | `true` or `false` |
| `indexOf(e)` | Finds the first index of `e` | the index, or `-1` |
| `lastIndexOf(e)` | Finds the last index of `e` | the index, or `-1` |
| `size()` | Counts the elements | a number |
| `isEmpty()` | Checks whether size is 0 | `true` or `false` |
| `clear()` | Removes every element | nothing |
Notice that remove("rinse") removed only the first "rinse". The second one stayed. Note also that contains, indexOf, and remove(e) compare elements with the equals method. A later chapter explains how equals works for your own classes.
When an index is out of range
If you ask for an index that does not exist, Java throws an exception. An exception is an error object that stops the program unless you catch it. For lists, this one is called IndexOutOfBoundsException.
import java.util.ArrayList;
import java.util.List;
public class BoundsDemo {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
names.add("Ana");
try {
names.get(1); // only index 0 exists
} catch (IndexOutOfBoundsException e) {
System.out.println("No element at index 1");
}
names.add(1, "Ben"); // allowed: index equal to size adds at the end
System.out.println(names); // [Ana, Ben]
try {
names.add(5, "Cara"); // not allowed: would leave a gap
} catch (IndexOutOfBoundsException e) {
System.out.println("Cannot insert at index 5");
}
}
}The rules for valid indexes are:
- For
get,set, andremove(i), the index must be from0tosize() - 1. - For
add(i, e), the index can be from0tosize(). Usingsize()adds at the end. - An empty list has no valid index for
get. Evenget(0)fails.
How ArrayList works inside
The name ArrayList tells you how it works. Inside, it keeps a normal Java array. That array is usually larger than the list, so there is spare room. The size of the inner array is called the capacity.
When you add an element and there is spare room, the list puts it in the next free slot. That is fast. When the inner array is full, the list creates a new, bigger array (about 1.5 times larger) and copies every element across. Copying takes time, but it happens rarely, so adding at the end is fast on average.
The inner array also explains which operations are fast and which are slow:
| Operation | Speed | Why |
|---|---|---|
| `get(i)`, `set(i, e)` | Fast | Jumps straight to slot `i` |
| `add(e)` at the end | Fast on average | Usually a free slot is ready |
| `add(0, e)` or `remove(0)` | Slow for big lists | Every other element must shift one place |
| `contains(e)`, `indexOf(e)` | Slow for big lists | Checks elements one by one from the start |
For a list of 10 elements, none of this matters. For a list of a million elements, inserting at the front a million times can be very slow. The chapter on LinkedList and the chapter on choosing a collection return to this trade-off.
Common mistakes
- Starting at index 1. The first element is
get(0). A loop that runs toi <= size()goes one step too far and throws an exception. - Mixing up
setandadd(i, e).setreplaces an element and keeps the size the same.add(i, e)inserts a new element and makes the list longer. - Expecting
remove(e)to remove every copy. It removes only the first match. - Forgetting that
indexOfreturns-1. Check for-1before you use the result as an index.
Exercise
Start with an empty List<String> called colors. Run these calls in order: add("red"), add("blue"), add(0, "green"), set(2, "yellow"), add("red"). What does System.out.println(colors) print, and what is colors.indexOf("red")?
Show answer
After add("red") and add("blue") the list is [red, blue]. add(0, "green") gives [green, red, blue]. set(2, "yellow") replaces blue, giving [green, red, yellow]. add("red") gives [green, red, yellow, red]. It prints [green, red, yellow, red], and indexOf("red") is 1 because indexOf returns the first match.
Exercise
A list has size 4. Which of these calls throw IndexOutOfBoundsException: get(4), add(4, "x"), set(0, "x"), remove(-1)?
Show answer
get(4) throws, because valid indexes for get are 0 to 3. add(4, "x") is allowed, because add accepts an index equal to the size and appends at the end. set(0, "x") is allowed. remove(-1) throws, because negative indexes are never valid.
Exercise
Write a main method that builds a List<String> with "a", "b", "a", "c", "a", then removes every "a" using only remove(Object) in a while loop, and prints the result.
Show answer
Use the boolean that remove returns: List<String> list = new ArrayList<>(); list.add("a"); list.add("b"); list.add("a"); list.add("c"); list.add("a"); while (list.remove("a")) { } System.out.println(list); This prints [b, c]. Each call removes the first "a" and returns true, and the loop stops when remove returns false.