⚡IntermediateCollections Framework

ArrayList

Use ArrayList to store a resizable list of objects, and master the most common List operations.

Overview

ArrayList is the most commonly used collection in Java. Unlike a plain array, it resizes automatically as you add or remove elements. It lives in java.util and implements the List interface. ArrayList stores objects (not primitives directly, though autoboxing handles int to Integer transparently). Elements maintain insertion order and duplicates are allowed. Random access by index is fast (O(1)), while inserting or removing in the middle is slower (O(n)) because elements must shift. Always declare the variable as List<E> (the interface) rather than ArrayList<E> to keep your code flexible.

Key Points

  • •Import java.util.ArrayList and java.util.List
  • •Declare as List<String> list = new ArrayList<>() for flexibility
  • •add(item) appends to the end; add(index, item) inserts at a position
  • •get(index) retrieves; set(index, item) replaces; remove(index) deletes
  • •size() returns the count; isEmpty() checks for empty
  • •contains(item) and indexOf(item) for searching
  • •for-each loop or iterator for traversal
  • •Collections.sort(list) or list.sort(Comparator) for sorting

Examples

Creating and manipulating an ArrayList

import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<String> fruits = new ArrayList<>();

        // Adding elements
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Cherry");
        fruits.add(1, "Blueberry"); // insert at index 1

        System.out.println(fruits); // [Apple, Blueberry, Banana, Cherry]
        System.out.println("Size: " + fruits.size());
        System.out.println("Get index 2: " + fruits.get(2));

        // Modifying
        fruits.set(0, "Avocado");
        fruits.remove("Banana");
        fruits.remove(2); // remove by index

        System.out.println(fruits); // [Avocado, Blueberry]
    }
}

remove(int) removes by index; remove(Object) removes by value. Use Integer.valueOf(n) to remove by value when storing integers.

Iterating and searching

import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Integer> scores = new ArrayList<>();
        scores.add(85);
        scores.add(92);
        scores.add(78);
        scores.add(95);
        scores.add(88);

        // For-each
        int total = 0;
        for (int score : scores) {
            total += score;
        }
        System.out.println("Average: " + (total / scores.size()));

        // Searching
        System.out.println("Contains 92: " + scores.contains(92));
        System.out.println("Index of 78: " + scores.indexOf(78));

        // Remove elements matching condition (Java 8+)
        scores.removeIf(s -> s < 85);
        System.out.println("After removeIf < 85: " + scores);
    }
}

removeIf takes a predicate (lambda). It removes all elements where the condition is true.

Sorting and converting

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<String> names = new ArrayList<>();
        names.add("Charlie");
        names.add("Alice");
        names.add("Bob");

        Collections.sort(names);
        System.out.println("Sorted: " + names);

        Collections.reverse(names);
        System.out.println("Reversed: " + names);

        // Convert array to List
        String[] arr = {"X", "Y", "Z"};
        List<String> fromArray = new ArrayList<>(List.of(arr));
        System.out.println("From array: " + fromArray);

        // Convert List to array
        String[] backToArray = names.toArray(new String[0]);
        System.out.println("Array length: " + backToArray.length);
    }
}

List.of() creates an immutable list. Wrap it in new ArrayList<>() if you need to modify it.

Common Mistakes

  • Calling remove(int index) when you want to remove a specific Integer value. Cast to remove by value: list.remove(Integer.valueOf(5))
  • Modifying a list while iterating with for-each, which throws ConcurrentModificationException. Use removeIf or an iterator instead
  • Declaring the variable as ArrayList instead of List, which makes it harder to swap implementations later

Note

Prefer List.of("a","b","c") to create a small read-only list quickly. Wrap it in new ArrayList<>() only if you need to add or remove elements later.

Exercises

Write Java code and click Run to execute it instantly. When your output looks correct, mark as done.

Loading editor…

Completed: 0 / 4 exercises

Knowledge Check

Question 1 of 4

What does ArrayList.remove(2) do?