[!NOTE] In chapter 6, we learned about standard Arrays (e.g.,
String[] cars = new String[5];). Standard arrays are incredibly fast, but they have a fatal flaw: their size cannot be changed once created.
If you don't know how many users will sign up for your application today, you cannot use a strictly sized array. You need a data structure that dynamically grows or shrinks instantly as data is added or removed.
Introducing ArrayList
The ArrayList class is a resizable array, which is completely built-in to the java.util package.
Under the hood, an ArrayList is secretly just a standard [] array. When it gets full, Java silently creates a brand new array double the size in memory, copies all the old data over rapidly, and destroys the old array without bothering you.
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
// 1. Creation. We MUST use the primitive wrapper class (Integer, not int)!
ArrayList<String> cars = new ArrayList<String>();
// 2. Dynamic Addition. We didn't specify a size limit!
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
// 3. Retrieval. (We use .get() instead of standard [0] brackets)
System.out.println(cars.get(0)); // Outputs "Volvo"
// 4. Modification
cars.set(0, "Opel");
// 5. Deletion. All elements automatically shift to fill the gap safely!
cars.remove(1); // Deletes BMW
// 6. Checking dynamic size
System.out.println(cars.size()); // Outputs 3
}
}
Primitive Wrapper Classes
An annoying quirk of ArrayList is that it can only store fully-featured Objects on the Heap. It physically cannot store stack-based primitive variables like int, double, or boolean.
To fix this, Java provides Object wrappers for all primitives. They act identically, but cost slightly more memory.
- Use
Integerinstead ofint - Use
Doubleinstead ofdouble - Use
Booleaninstead ofboolean - Use
Characterinstead ofchar
// ERROR: Syntax error on token "int", Dimensions expected!
// ArrayList<int> myNumber = new ArrayList<int>();
// CORRECT!
ArrayList<Integer> myNumbers = new ArrayList<Integer>();
myNumbers.add(5);
myNumbers.add(10);
Looping through ArrayLists
Just like arrays, you can use a classic loop or an enhanced for-each loop.
Notice how we use .size() instead of .length!
for (String car : cars) {
System.out.println(car);
}