Java ArrayList Basics: Dynamic Array Operations, A Must-Learn for Beginners

1. What is ArrayList?

In Java, ArrayList is a class in the java.util package that implements the functionality of a dynamic array. Simply put, ArrayList is like an automatically resizable array—you don’t need to manually specify its length. When the number of elements exceeds the current capacity, it automatically “grows,” and you can add or remove elements at any time, making it very flexible.

Compared to a regular array (e.g., int[]), the core advantage of ArrayList is its variable length. It also provides a series of convenient methods for element operations (addition, deletion, modification, search, traversal, etc.), making it suitable for storing and managing data collections with an uncertain length.

2. Why Choose ArrayList?

Suppose you need to store a class’s student list:
- With a regular array, you must first define a fixed length (e.g., String[] students = new String[50]), but the number of students may exceed or be less than 50, leading to either wasted space or array out-of-bounds errors.
- With ArrayList, you can directly create an empty list using new ArrayList<String>(), and then add students at any time with the add() method—no need to worry about length constraints.

Additionally, ArrayList encapsulates many practical methods (e.g., sorting, searching), simplifying operations and eliminating the need to repeatedly write complex array-related logic.

3. Basic Operations: Creation and Initialization

To use ArrayList, first import java.util.ArrayList, then create an object via a constructor. Generics (<E>) specify the type of elements in the list (e.g., strings, integers) to avoid type errors.

import java.util.ArrayList; // Import the ArrayList class

public class ArrayListDemo {
    public static void main(String[] args) {
        // Create an ArrayList storing String elements (empty list)
        ArrayList<String> fruits = new ArrayList<>();

        // Optionally specify an initial capacity (reduces expansion frequency if planned in advance)
        ArrayList<Integer> numbers = new ArrayList<>(10); // Initial capacity = 10
    }
}

4. Adding Elements: add() Method

Use add(E e) to append elements to the end of the list, or add(int index, E e) to insert an element at a specific position.

// 1. Add elements to the end
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");

// 2. Insert an element at a specific position (e.g., insert "Watermelon" at index 1)
fruits.add(1, "Watermelon"); 

// Current list content: [Apple, Watermelon, Banana, Orange]

5. Retrieving Elements: get() Method

Use get(int index) to retrieve an element at a specified position. Indices start at 0 (an IndexOutOfBoundsException is thrown if the index is negative or exceeds the list length).

// Get the first element (index 0)
String first = fruits.get(0); // "Apple"

// Get the last element (index = size()-1)
String last = fruits.get(fruits.size() - 1); // "Orange"

6. Modifying Elements: set() Method

Use set(int index, E element) to replace an element at a specified position and return the old element.

// Replace the element at index 1 ("Watermelon") with "Grape"
String oldElement = fruits.set(1, "Grape"); 
// Updated list: [Apple, Grape, Banana, Orange]
// oldElement is "Watermelon"

7. Removing Elements: remove() Method

There are two ways to remove elements:
- remove(int index): Deletes the element at the specified index and returns the removed element.
- remove(Object o): Deletes the first occurrence of an element matching o (only the first match if duplicates exist).

// 1. Remove the element at index 2 ("Banana")
String removed = fruits.remove(2); // Returns "Banana"
// Updated list: [Apple, Grape, Orange]

// 2. Remove the element "Orange" (note: type must match the list)
fruits.remove("Orange"); 
// Updated list: [Apple, Grape]

8. Traversing ArrayList: How to Print All Elements?

Traversal is a core scenario for using lists. Common methods include:

Method 1: Regular For Loop (via Index)

for (int i = 0; i < fruits.size(); i++) {
    System.out.println(fruits.get(i)); // Print elements one by one
}

Method 2: Enhanced For Loop (For-Each)

Suitable for scenarios where you only need to traverse elements without modifying indices.

for (String fruit : fruits) {
    System.out.println(fruit); // Directly iterate over elements
}

Method 3: Iterator

Suitable for scenarios where you need to remove elements while traversing (regular for loops cause index errors when removing elements).

import java.util.Iterator;

Iterator<String> iterator = fruits.iterator();
while (iterator.hasNext()) {
    String fruit = iterator.next();
    System.out.println(fruit);
    // To remove elements during traversal:
    // if (fruit.equals("Grape")) iterator.remove();
}

9. Dynamic Expansion: What If Capacity Is Insufficient?

ArrayList automatically expands when adding elements exceeds the current capacity: it creates a new array (initial capacity = 10, then expands to ~1.5x the original capacity each time) and copies the old array’s elements to the new array.

For example:
- Initial capacity = 10; after adding 10 elements, the list is full.
- When adding the 11th element, the capacity automatically expands to 15 (10 × 1.5), and all elements are copied to the new array.

Note: Expansion is automatic and requires no manual handling—it’s one of ArrayList’s core advantages (no need to worry about “the array is full”).

10. Precautions

  • Index Out-of-Bounds: Indices must be between 0 and size()-1. Otherwise, an error is thrown (e.g., get(-1) or remove(5) when the list has only 3 elements).
  • Generics Constraints: The element type specified during creation (e.g., <String>) must be consistent; otherwise, a compilation error occurs (no other type elements can be added).
  • Duplicate Elements: remove(Object o) deletes only the first matching element (duplicates require multiple calls).

11. Complete Example

import java.util.ArrayList;
import java.util.Iterator;

public class ArrayListFullDemo {
    public static void main(String[] args) {
        // 1. Create a list
        ArrayList<String> animals = new ArrayList<>();

        // 2. Add elements
        animals.add("Cat");
        animals.add("Dog");
        animals.add("Rabbit");
        System.out.println("Initial list: " + animals); // [Cat, Dog, Rabbit]

        // 3. Modify an element
        animals.set(1, "Tiger"); // Replace "Dog" at index 1 with "Tiger"
        System.out.println("After modification: " + animals); // [Cat, Tiger, Rabbit]

        // 4. Remove an element
        animals.remove(0); // Remove "Cat" at index 0
        System.out.println("After removal: " + animals); // [Tiger, Rabbit]

        // 5. Traverse elements (enhanced for loop)
        System.out.println("Traversing elements:");
        for (String animal : animals) {
            System.out.println(animal);
        }

        // 6. Traverse with an iterator
        System.out.println("Traversing with iterator:");
        Iterator<String> it = animals.iterator();
        while (it.hasNext()) {
            System.out.println(it.next());
        }
    }
}

Summary

ArrayList is the most basic and commonly used dynamic array tool in Java. Mastering its core operations (addition, deletion, modification, search, traversal) helps you quickly handle data with an uncertain length. Remember: flexibility, automatic expansion, and no need to manage capacity are its three key advantages. Practice scenarios like storing student information or product lists to become proficient!

For more advanced operations (e.g., sorting, searching), you can learn about the Collections utility class or other ArrayList methods later—solid foundations are always essential.

Xiaoye