ArrayList: The Resizable Dynamic Array
In the previous lesson, you discovered the superpower and the Achilles' heel of standard Java arrays:
- Superpower: Blindingly fast random access because elements are contiguous in memory.
- Achilles' Heel: Their size is fixed permanently at creation.
In real-world applications, you almost never know the exact number of elements in advance:
- An e-commerce shopping cart: A user might add 1 item, or 15 items, or remove 2 items.
- A chat application: Messages arrive continuously.
- A music playlist: Songs are queued, shuffled, and deleted dynamically.
If you had to use standard arrays, you would constantly write complex code to create new arrays, copy elements, and adjust capacities manually.
Java provides a built-in, highly optimized class in java.util that solves this completely: ArrayList.
1. What Is an ArrayList?
An ArrayList is a resizable, dynamic array that grows and shrinks automatically as you add or remove elements.
Everyday Analogy: Fixed Bus vs Train of Carriages 🚆
- Standard Array: A city bus with exactly 40 welded seats. If a 41st passenger boards, they cannot sit. You would need to commission an entirely new bus.
- ArrayList: A train. When more passengers arrive, the train operator simply hitches an extra carriage onto the back. When people leave, carriages can be decoupled. You never worry about running out of seats!
2. Importing and Declaring an ArrayList
Because ArrayList is part of the Java Collections Framework, you must import it at the top of your Java file:
import java.util.ArrayList;The Angle Brackets Syntax <T> (Generics):
ArrayList<String> fruits = new ArrayList<String>();// Or using the modern Java 7+ "Diamond Operator" <>:ArrayList<String> fruits = new ArrayList<>();Notice <String> inside the angle brackets. This specifies the type of elements the list will hold. It tells the Java compiler: "This list is strictly for Strings. Prevent anyone from accidentally putting an integer or car object inside it."
3. The Primitives Trap: Wrapper Classes & Autoboxing ⚠️
Try typing this line in Java:
ArrayList<int> numbers = new ArrayList<>(); // ❌ COMPILE ERROR!Compiler Error:
Syntax error: Dimensions expected after the type 'int' (Primitive types not allowed as type arguments)
Why can't we write ArrayList<int>?
The Java Collections Framework was architected strictly to work with Objects on the Heap, not raw primitive values (int, double, boolean, char).
To solve this, Java provides an Object counterpart called a Wrapper Class for every single primitive type:
| Primitive Type | Wrapper Class (Object) | ArrayList Declaration |
|---|---|---|
int | Integer | ArrayList<Integer> numbers = new ArrayList<>(); |
double | Double | ArrayList<Double> prices = new ArrayList<>(); |
boolean | Boolean | ArrayList<Boolean> flags = new ArrayList<>(); |
char | Character | ArrayList<Character> letters = new ArrayList<>(); |
long | Long | ArrayList<Long> ids = new ArrayList<>(); |
What is Autoboxing and Unboxing? 🎁
You might worry: "Does that mean I have to manually wrap my numbers into objects every time?"
No! Java handles this automatically:
- Autoboxing: Java automatically converts a primitive
intinto anIntegerobject when adding it to a list:ArrayList<Integer> list = new ArrayList<>();list.add(42); // Automatically converted to Integer.valueOf(42) - Unboxing: Java automatically extracts the primitive
intfrom theIntegerobject when you retrieve it:int value = list.get(0); // Automatically calls .intValue()
4. Complete CRUD Operations Cheatsheet
ArrayList provides intuitive, powerful methods for creating, reading, updating, and deleting elements (CRUD):
Operation Method Call Description
─────────────────────────────────────────────────────────────────────────────
Create (Add) list.add("Apple") Appends element to the end
Insert At Index list.add(1, "Mango") Inserts at index 1 (shifts rest right)
Read (Get) list.get(0) Returns element at index 0
Update (Set) list.set(2, "Orange") Replaces element at index 2
Delete by Index list.remove(0) Removes element at index 0 (shifts rest left)
Delete by Value list.remove("Apple") Removes first matching object
Check Size list.size() Returns total number of elements
Check Existence list.contains("Mango") Returns true if element exists
Clear All list.clear() Wipes all elements (size becomes 0)
Check if Empty list.isEmpty() Returns true if size == 0
Let's see them in action:
import java.util.ArrayList;public class Main { public static void main(String[] args) { ArrayList<String> tasks = new ArrayList<>(); // 1. ADD (Create) tasks.add("Buy groceries"); tasks.add("Read Java book"); tasks.add("Go for a run"); System.out.println("Initial List: " + tasks); // [Buy groceries, Read Java book, Go for a run] // 2. INSERT at specific index tasks.add(1, "Pay electric bill"); // Inserts at index 1 System.out.println("After Insert: " + tasks); // [Buy groceries, Pay electric bill, Read Java book, Go for a run] // 3. GET (Read) String firstTask = tasks.get(0); System.out.println("First task: " + firstTask); // Buy groceries // 4. SET (Update) tasks.set(2, "Study Data Structures"); // Replaces index 2 System.out.println("After Update: " + tasks); // 5. REMOVE (Delete) tasks.remove(0); // Removes index 0 ("Buy groceries") System.out.println("After Removing index 0: " + tasks); // 6. UTILITY METHODS System.out.println("Total tasks: " + tasks.size()); // 3 System.out.println("Contains 'Go for a run'? " + tasks.contains("Go for a run")); // true }}5. Under the Hood: How ArrayList Actually Grows 📈
Here is a secret that surprises many beginners:
An
ArrayListis NOT magic. Internally, it is powered by a standard, fixed-size Java array!
If an ArrayList is just a normal array under the hood, how does it grow?
The Geometric Resizing Algorithm:
- When you instantiate
new ArrayList<>(), Java creates an internal private array with a default initial capacity (typically 10 slots):Internal Buffer: [ null, null, null, null, null, null, null, null, null, null ] Size: 0, Capacity: 10 - You add 10 items. The array is now 100% full.
- You call
list.add("11th Item"). What happens?- Java allocates a new, larger array on the Heap with 1.5x capacity (15 slots).
- Java copies all 10 old elements over to the new array using high-speed native memory copying (
System.arraycopy). - Java appends the 11th item into slot 10.
- The old 10-slot array is abandoned for the Garbage Collector.
Step 1: Old Array is Full (Capacity 10)
┌───┬───┬───┬───┬───┬───┬───┬───┬───┬───┐
│ 1 │ 2 │ 3 │ 4 │ 5 │ 6 │ 7 │ 8 │ 9 │ 10│
└───┴───┴───┴───┴───┴───┴───┴───┴───┴───┘
│
▼ (Grow by ~1.5x: Capacity becomes 15)
Step 2: Allocate New Array & Copy Elements
┌───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┐
│ 1 │ 2 │ 3 │ 4 │ 5 │ 6 │ 7 │ 8 │ 9 │ 10│ 11│ │ │ │ │
└───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┘
Interactive ArrayList Resizing Simulator 🕹️
Try adding elements to the list below. When capacity fills up, watch Java automatically allocate a larger array (), copy elements over, and discard the old array:
Object[] elementData = new Object[4]Capacity: 4Why 1.5x Geometric Growth? If Java expanded by only +1 slot on every append, adding 10,000 items would require copying arrays 10,000 times (catastrophic $O(N^2)$ slowdown). By multiplying capacity by 1.5x, copies happen exponentially less often, giving `ArrayList.add()` an amortized $O(1)$ constant time.
Because capacity grows geometrically (multiplying by 1.5x), array reallocations become exponentially rarer as the list grows. This guarantees that appending an item has an Amortized constant time complexity!
6. Array vs. ArrayList: Complete Head-to-Head Comparison
| Feature | Standard Array (T[]) | ArrayList<T> |
|---|---|---|
| Size / Capacity | Strictly Fixed at creation | Dynamic: expands and shrinks automatically |
| Primitives | Direct storage (int[], double[]) | Requires Wrapper Objects (Integer, Double) |
| Access Syntax | arr[i] | list.get(i) |
| Modify Syntax | arr[i] = val | list.set(i, val) |
| Add / Remove | Not supported dynamically | list.add(val), list.remove(i) |
| Length Check | arr.length (field property) | list.size() (method call) |
| Memory Overhead | Minimal (pure data values) | Slight overhead (object headers + extra capacity buffer) |
| Performance | Maximum hardware speed | Extremely fast, minor boxing/method call overhead |
7. Iterating Through an ArrayList
Just like standard arrays, you can traverse an ArrayList in multiple ways:
ArrayList<String> heroes = new ArrayList<>();heroes.add("Spider-Man");heroes.add("Iron Man");heroes.add("Thor");// 1. Traditional for loop (with index)for (int i = 0; i < heroes.size(); i++) { System.out.println(i + ": " + heroes.get(i));}// 2. Enhanced for-each loop (clean and idiomatic)for (String hero : heroes) { System.out.println("Hero: " + hero);}// 3. Modern Lambda forEach (Java 8+)heroes.forEach(hero -> System.out.println("Super: " + hero));8. Complete Real-World Program: Shopping Cart System
Let's put everything together into a practical shopping cart application:
// File: ShoppingCartDemo.javaimport java.util.ArrayList;class Item { String name; double price; Item(String name, double price) { this.name = name; this.price = price; }}class ShoppingCart { ArrayList<Item> items = new ArrayList<>(); void addItem(Item item) { items.add(item); System.out.println("Added to cart: " + item.name + " (₹" + item.price + ")"); } void removeItem(int index) { if (index >= 0 && index < items.size()) { Item removed = items.remove(index); System.out.println("Removed from cart: " + removed.name); } else { System.out.println("Invalid cart index!"); } } double calculateTotal() { double total = 0.0; for (Item item : items) { total += item.price; } return total; } void printReceipt() { System.out.println("\n--- RECEIPT ---"); for (int i = 0; i < items.size(); i++) { System.out.println((i + 1) + ". " + items.get(i).name + " - ₹" + items.get(i).price); } System.out.println("----------------"); System.out.printf("Total Amount Due: ₹%.2f\n", calculateTotal()); }}public class Main { public static void main(String[] args) { ShoppingCart cart = new ShoppingCart(); cart.addItem(new Item("Mechanical Keyboard", 2499.00)); cart.addItem(new Item("Wireless Mouse", 899.00)); cart.addItem(new Item("USB-C Hub", 1299.00)); // User changes mind about the mouse (index 1) cart.removeItem(1); cart.printReceipt(); }}Console Output:
Added to cart: Mechanical Keyboard (₹2499.0)
Added to cart: Wireless Mouse (₹899.0)
Added to cart: USB-C Hub (₹1299.0)
Removed from cart: Wireless Mouse
--- RECEIPT ---
1. Mechanical Keyboard - ₹2499.0
2. USB-C Hub - ₹1299.0
----------------
Total Amount Due: ₹3798.00
9. Beginner Summary Checklist
ArrayListis a dynamic, auto-resizing array that grows and shrinks as needed.- Must be imported from
java.util.ArrayList. - Uses generics:
ArrayList<Type> list = new ArrayList<>();. - Cannot store primitives directly; uses Wrapper classes (
Integer,Double,Boolean). - Java handles conversion automatically via Autoboxing and Unboxing.
- Use
add(),get(),set(),remove(), andsize(). - Internally backed by a fixed array that grows by roughly 1.5x when full (Amortized appends).
- Use
arr.lengthfor standard arrays, butlist.size()for ArrayLists!