[!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);
}
Choosing Between Array and ArrayList
Arrays are fixed and simple. ArrayList is flexible and usually easier for application code. In most beginner projects, if the number of items can change, use ArrayList.
Common ArrayList Operations
ArrayList<String> names = new ArrayList<>();
names.add("Asha");
names.add("Ravi");
names.add("Meera");
names.set(1, "Rahul");
boolean hasAsha = names.contains("Asha");
int count = names.size();
Use the Interface Type
List<String> names = new ArrayList<>();
Declaring the variable as List keeps your code flexible. You can change the implementation later if needed without changing most callers.
Common Mistakes
- Using
list.lengthinstead oflist.size(). - Using array brackets with
ArrayListinstead ofget()andset(). - Removing items in a for-each loop.
- Choosing
LinkedListbecause it sounds more advanced.
Mini Practice
Create a shopping list with ArrayList. Add five items, update one item, remove one item, and print the final count and contents.
Practice Lab: Shopping List Manager
Use ArrayList for a list whose size changes.
- Create an
ArrayList<String>namedshoppingList. - Add five items.
- Update the second item with
set. - Remove one item by value or index.
- Print the final list and total count.
Goal: Practice dynamic list operations: add, get, set, remove, and size.
Revision Checkpoint
- Array: Fixed size and index-based.
ArrayList: Dynamic size backed by an array internally.add: Adds an item.get/set: Read or update by index.size(): Collection count, unlike arraylength.
Before the quiz: Decide whether fixed-size array or dynamic list is better for a changing shopping cart.