ArrayList Methods
A list that grows and shrinks: creating an ArrayList with a type parameter, and the methods size, add, get, set, and remove, including how inserting and removing shift the other elements.
An ArrayList object is mutable in size and contains object references. Unlike an array, its size changes as elements are added and removed. The constructor ArrayList() constructs an empty list, and the generic type ArrayList<E> names the element type so the compiler can catch mistakes. The class is in java.util and must be imported. Its methods size, add, get, set, and remove read and change the list; indices run from 0 to the number of elements minus 1.
1What an ArrayList Is
Arrays have a fixed length, which is awkward when the amount of data is not known in advance or changes while the program runs. An ArrayList object is mutable in size: adding an element makes it one longer, and removing one makes it one shorter. Like an array, it keeps its elements in order, and each has an index starting at 0.
An ArrayList contains object references, never primitives. A list of words is an ArrayList<String>; a list of whole numbers is an ArrayList<Integer>, with autoboxing converting int values as they are added and unboxing converting them back when they are read into int variables.
ArrayList object is mutable in size and contains object references, unlike an array, whose length is fixed when it is created.| Array | ArrayList | |
|---|---|---|
| Size | Fixed at creation: a.length | Changes: list.size() |
| Element types | Primitives or references | References only (use Integer, Double for numbers) |
| Read | a[i] | list.get(i) |
| Write | a[i] = v; | list.set(i, v); |
| Bad index | ArrayIndexOutOfBoundsException | IndexOutOfBoundsException |
| Import needed | No | Yes: java.util.ArrayList |
2Creating a List
The ArrayList class is part of the java.util package, so an import statement must be used to make it available: import java.util.ArrayList;. The constructor ArrayList() constructs an empty list, whose size is 0.
Java allows the generic type ArrayList<E>, where the type parameter E specifies the type of the elements. When ArrayList<E> is specified, the types of the reference parameters and return type when using the methods are type E. ArrayList<E> is preferred over plain ArrayList; for example, ArrayList<String> names = new ArrayList<String>(); allows the compiler to find errors that would otherwise be found at run time.
Building a List
Predict the output.
ArrayList<String> trees = new ArrayList<String>();
System.out.println(trees.size());
trees.add("pine");
trees.add("oak");
trees.add("elm");
System.out.println(trees.size());
System.out.println(trees.get(0) + " " + trees.get(2));
System.out.println(trees);
0
3
pine elm
[pine, oak, elm]
- 1
new ArrayList<String>()constructs an empty list of strings: size 0. - 2
add(obj)appends to the end each time; after three calls the size is 3. - 3
get(index)reads by index, starting at 0. - 4Printing the list shows its elements in brackets.
ArrayList starts empty and grows as elements are added.The Compiler Checks the Element Type
Explain the compile error.
ArrayList<String> trees = new ArrayList<String>();
trees.add("pine");
trees.add(42);
- 1
ArrayList<String>declares that every element is aString. - 2
add(42)tries to add anint, which cannot become aString, so the compiler rejects it. - 3This is the benefit of the type parameter: the mistake is caught when compiling instead of causing a failure while the program runs.
ArrayList<E> lets the compiler find errors that would otherwise be found at run time.3Adding Elements
There are two add methods. boolean add(E obj) appends obj to the end of the list and returns true. void add(int index, E obj) inserts obj at position index, where 0 ≤ index ≤ size(), moving the elements at position index and higher to the right, adding 1 to their indices, and adding 1 to the size.
Inserting at index 0 puts the new element first; inserting at an index equal to the current size appends it, exactly like the one-argument add. Any index greater than the size, or negative, throws an IndexOutOfBoundsException.
Appending is the most common way to build a list, for example while reading values from a file, because the program does not need to know in advance how many values there will be. Inserting at a specific position is useful for keeping a list in order as new elements arrive.
add(int index, E obj) inserts at index, moving elements at that position and higher to the right and adding 1 to the size.| Method | What it does | Returns |
|---|---|---|
ArrayList() | Constructs an empty list | — |
int size() | Number of elements | The size |
boolean add(E obj) | Appends obj to the end | true |
void add(int index, E obj) | Inserts at index (0 ≤ index ≤ size); later elements move right | — |
E get(int index) | Reads the element at index | That element |
E set(int index, E obj) | Replaces the element at index | The element formerly there |
E remove(int index) | Removes the element at index; later elements move left | The removed element |
add With an Index
Predict the output.
ArrayList<String> trees = new ArrayList<String>();
trees.add("pine");
trees.add("oak");
trees.add("elm");
trees.add(1, "fir");
trees.add(4, "ash");
System.out.println(trees);
System.out.println(trees.size());
[pine, fir, oak, elm, ash]
5
- 1
add(1, "fir")inserts at index 1; oak and elm move right (Figure 2). - 2
add(4, "ash")uses index 4, which equals the size at that moment, so it appends at the end. Valid insert positions are 0 throughsize().
add(index, obj) inserts and shifts later elements right; an index equal to the size appends.After add(1, "fir"), the element that was at index 1 is now at index 2. Any index saved before the insertion may now point at a different element. Re-read positions after inserting.
4Reading and Replacing
E get(int index) returns the element at position index in the list without changing anything. E set(int index, E obj) replaces the element at position index with obj and returns the element formerly at that position; the size does not change.
These two methods play the roles that a[i] and a[i] = v play for arrays. The return value of set is often ignored, but it is useful when a program needs to know what was replaced, for example to swap two elements or to record a change.
Elements of a list of objects can also be used directly: trees.get(0).length() calls a String method on the first element. When the list holds mutable objects, calling a mutator on an element returned by get changes the object stored in the list, because get returns the reference, not a copy.
get(int index) returns the element at index; set(int index, E obj) replaces it and returns the element formerly at that position.set Returns the Old Value
Predict the output.
ArrayList<String> trees = new ArrayList<String>();
trees.add("pine");
trees.add("oak");
trees.add("elm");
String old = trees.set(0, "yew");
System.out.println(old);
System.out.println(trees);
System.out.println(trees.size());
pine
[yew, oak, elm]
3
- 1
set(0, "yew")replaces the element at index 0. - 2It returns the element formerly there, "pine", which is stored in
old. - 3The size does not change.
set replaces an element and returns the one it replaced.ArrayList and Autoboxing
Predict the output. Watch what remove(1) means.
ArrayList<Integer> scores = new ArrayList<Integer>();
scores.add(80);
scores.add(1);
scores.add(95);
int first = scores.get(0);
scores.remove(1);
System.out.println(first + scores.get(0));
System.out.println(scores);
160
[80, 95]
- 1Wrapper type. An
ArrayListholds object references, so a list of whole numbers isArrayList<Integer>;add(80)autoboxes. - 2Unboxing.
int first = scores.get(0);unboxes 80. - 3
remove(1)removes by index: the element at index 1 (the value 1), not the value 1 wherever it is. - 4Result. 80 + 80 = 160, and the list is [80, 95].
Integer or Double as the element type, with autoboxing and unboxing handling conversions.5Removing Elements
E remove(int index) removes the element from position index, moving elements at position index + 1 and higher to the left, subtracting 1 from their indices, and subtracting 1 from the size. It returns the element formerly at position index, so the removed value can still be used.
For an ArrayList<Integer>, remove(1) removes the element at index 1, not the value 1. Keeping that distinction in mind avoids a common surprise when lists hold small whole numbers.
remove(int index) removes the element at index, moves higher elements to the left, subtracts 1 from the size, and returns the removed element.| Statement | List afterward | size() |
|---|---|---|
| new ArrayList<String>() | [] | 0 |
| add("pine"), add("oak"), add("elm") | [pine, oak, elm] | 3 |
| add(1, "fir") | [pine, fir, oak, elm] | 4 |
| set(0, "yew") | [yew, fir, oak, elm] | 4 |
| remove(1) | [yew, oak, elm] | 3 |
remove Returns What It Took Out
Predict the output.
ArrayList<String> trees = new ArrayList<String>();
trees.add("pine");
trees.add("fir");
trees.add("oak");
trees.add("elm");
String gone = trees.remove(1);
System.out.println(gone);
System.out.println(trees);
System.out.println(trees.get(1));
fir
[pine, oak, elm]
oak
- 1
remove(1)removes "fir" and returns it. - 2Elements shift left. "oak" moves from index 2 to index 1, and "elm" from 3 to 2 (Figure 4).
- 3Size shrinks from 4 to 3, so
get(1)is now "oak".
remove(index) deletes an element, shifts later elements left, and returns the removed element.Serving a Waiting List in Order
A waiting list is served from the front. Predict the output.
ArrayList<String> waiting = new ArrayList<String>();
waiting.add("table 4");
waiting.add("table 9");
waiting.add("table 2");
while (waiting.size() > 0)
{
String next = waiting.remove(0);
System.out.println("serving " + next + ", " + waiting.size() + " left");
}
serving table 4, 2 left
serving table 9, 1 left
serving table 2, 0 left
- 1
remove(0)takes the first element and returns it, so the program can use it. - 2Everything shifts left, so the next element is always at index 0.
- 3The loop condition asks for the current size every time; when the list is empty, the loop ends.
remove and the changing size() work together to process a list from the front.scores.remove(1) removes whatever is at index 1. To remove a particular value, first find its index with a traversal, then call remove with that index.
6Indices and Element Types
The indices for an ArrayList start at 0 and end at the number of elements minus 1. The last element is list.get(list.size() - 1). Using an index outside this range with get, set, or remove throws an IndexOutOfBoundsException; for add(index, obj), the size itself is also a valid index.
Because the size changes, code must always ask the list for its current size rather than remembering an old one. After a removal, every later element has a smaller index, and the list is one shorter; after an insertion, the reverse. This is the main source of errors when lists are modified inside loops.
Reading One Past the End
What happens?
ArrayList<String> trees = new ArrayList<String>();
trees.add("pine");
trees.add("oak");
System.out.println(trees.get(1));
System.out.println(trees.get(trees.size()));
- 1
get(1)is the last element: "oak". - 2
get(trees.size())isget(2), one past the end, so Java throws anIndexOutOfBoundsException.
IndexOutOfBoundsException. ArrayList indices start at 0 and end at the number of elements minus 1.list.get(list.size()) is always out of bounds. The last element is at list.size() - 1.
Arrays use the attribute length; strings use the method length(); an ArrayList uses the method size(). Using the wrong one does not compile.
Four Habits for ArrayList
1. Import and Type It
import java.util.ArrayList; ArrayList<E>.
2. size() Changes
Always ask for the current size.
3. Inserts Shift Right, Removes Shift Left
Indices move after every add or remove.
4. set and remove Return Values
The replaced or removed element.
An ArrayList object is mutable in size and contains object references. The constructor ArrayList() constructs an empty list. The generic type ArrayList<E>, where E specifies the element type, is preferred because it allows the compiler to find errors that would otherwise be found at run time. The class is part of the java.util package and must be imported. size() returns the number of elements; add(E obj) appends and returns true; add(int index, E obj) inserts, moving later elements right; get(int index) returns an element; set(int index, E obj) replaces an element and returns the old one; and remove(int index) removes an element, moving later elements left, and returns it. Indices start at 0 and end at the number of elements minus 1.