ArrayList: Dynamic Lists in Java

Introduction

ArrayList is the most common List implementation—a resizable array backing store with fast index access. This chapter covers creation, CRUD operations, traversal, and when to choose ArrayList vs arrays—using Generics for type safety.

Prerequisites

Create an ArrayList

java
import java.util.ArrayList;
import java.util.List;
 
List<String> fruits = new ArrayList<>();
List<String> preset = new ArrayList<>(List.of("apple", "banana"));

1) Add Elements

java
fruits.add("orange");
fruits.add(0, "grape");  // insert at index 0
fruits.addAll(List.of("mango", "kiwi"));

2) Access and Update

java
String first = fruits.get(0);
fruits.set(1, "blueberry");
System.out.println(fruits.size());

3) Remove Elements

java
fruits.remove("mango");     // by object (equals)
fruits.remove(0);           // by index
fruits.removeIf(s -> s.startsWith("k"));
fruits.clear();

4) Search and Check

java
boolean hasApple = fruits.contains("apple");
int index = fruits.indexOf("banana");
boolean empty = fruits.isEmpty();

5) Traverse

java
// Enhanced for
for (String fruit : fruits) {
    System.out.println(fruit);
}
 
// Indexed for
for (int i = 0; i < fruits.size(); i++) {
    System.out.println(i + ": " + fruits.get(i));
}
 
// forEach + lambda
fruits.forEach(System.out::println);

6) Sort and Reverse

java
import java.util.Collections;
 
Collections.sort(fruits);
Collections.reverse(fruits);
fruits.sort(String::compareToIgnoreCase);

7) ArrayList vs Array

Use ArrayListUse array
size unknown at startfixed size known
frequent add/remove at endprimitive int[] performance
rich list APIinterop with low-level APIs
java
int[] arr = {1, 2, 3};
List<Integer> list = new ArrayList<>();
for (int v : arr) {
    list.add(v);
}

Real Mini Example: Todo List

java
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
 
public class TodoListDemo {
    public static void main(String[] args) {
        List<String> todos = new ArrayList<>();
 
        try (Scanner scanner = new Scanner(System.in)) {
            todos.add("Learn ArrayList");
            todos.add("Practice HashMap");
 
            System.out.println("=== Todo List ===");
            for (int i = 0; i < todos.size(); i++) {
                System.out.println((i + 1) + ". " + todos.get(i));
            }
 
            todos.remove("Practice HashMap");
            todos.add("Build score project");
            System.out.println("After update: " + todos);
        }
    }
}

Common Beginner Mistakes

get with Wrong Index

IndexOutOfBoundsException—valid range 0 .. size-1.

remove(int) vs remove(Integer)

list.remove(1) removes index 1. To remove value 1, use list.remove(Integer.valueOf(1)).

Modifying List While foreach-ing

Use Iterator.remove() or removeIf, not enhanced-for + remove.

Mini Practice

Read five names from Scanner, store in ArrayList, print sorted.

What’s Next

Key-value data: HashMap.

FAQ

ArrayList vs LinkedList?

ArrayList for most cases. LinkedList when many inserts/removes in middle (rare for beginners).

Is ArrayList thread-safe?

No. Use Collections.synchronizedList or CopyOnWriteArrayList when needed.

Can I store primitives?

Use ArrayList<Integer> with autoboxing, or libraries like Eclipse Collections for primitive lists (advanced).

Initial capacity?

Optional new ArrayList<>(100) reduces resizing when size is known approximately.

Null elements?

ArrayList allows null entries unless you enforce otherwise.