Java ArrayList Tutorial: A Complete Beginner’s Guide

admin5 min read
In this tutorial
  1. Creating an ArrayList
  2. Adding, reading, updating and removing
  3. Looping over a list
  4. Removing items while looping
  5. Sorting and searching
  6. Lists of your own objects
  7. How ArrayList works inside
  8. Converting between arrays and lists
  9. Common mistakes
  10. Summary

An ArrayList is the list you will reach for most often in Java. It stores elements in order, grows automatically and gives fast access by index. If arrays feel rigid because their size is fixed, ArrayList is the answer.

In this tutorial you will create lists, add and remove items, loop over them, sort and search them, and avoid the mistakes beginners make most.

Creating an ArrayList

Import it from java.util and declare the element type in angle brackets:

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

List<String> names = new ArrayList<>();
names.add("Ada");
names.add("Linus");
System.out.println(names); // [Ada, Linus]

Two things to notice:

  • We declare the variable as List (the interface) rather than ArrayList. This keeps your code flexible: you can switch to another List implementation later without changing the code that uses it.
  • The <> on the right is the “diamond”. Java infers String from the left-hand side.

Collections hold objects, not primitives, so a list of numbers uses the wrapper type: List<Integer>, not List<int>. Java converts between int and Integer automatically (autoboxing).

Other ways to create a list

List<Integer> scores = new ArrayList<>(List.of(70, 85, 92)); // with initial values
List<String> fixed = List.of("Mon", "Tue", "Wed");           // immutable!
List<String> big = new ArrayList<>(10_000);                   // initial capacity hint

List.of(...) creates an immutable list. Calling add on it throws UnsupportedOperationException. Wrap it in new ArrayList<>(...) when you need to modify it.

Adding, reading, updating and removing

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

public class ListBasics {
    public static void main(String[] args) {
        List<String> cart = new ArrayList<>();
        cart.add("Rice");               // [Rice]
        cart.add("Beans");              // [Rice, Beans]
        cart.add(0, "Garri");           // insert at index 0: [Garri, Rice, Beans]

        System.out.println(cart.get(1));      // Rice
        System.out.println(cart.size());      // 3

        cart.set(2, "Plantain");        // replace: [Garri, Rice, Plantain]
        cart.remove("Rice");            // by value: [Garri, Plantain]
        cart.remove(0);                 // by index: [Plantain]

        System.out.println(cart.contains("Plantain")); // true
        System.out.println(cart.indexOf("Garri"));     // -1 (not found)
        System.out.println(cart.isEmpty());            // false

        cart.clear();
        System.out.println(cart);       // []
    }
}

The remove(int) trap with Integer lists

With a List<Integer>, remove(1) removes the element at index 1, not the value 1:

List<Integer> nums = new ArrayList<>(List.of(5, 1, 7));
nums.remove(1);                    // removes index 1 -> [5, 7]
nums.remove(Integer.valueOf(7));   // removes the value 7 -> [5]

Looping over a list

The enhanced for loop is the clearest way to read every element:

for (String item : cart) {
    System.out.println(item);
}

Use an index-based loop when you need the position:

for (int i = 0; i < cart.size(); i++) {
    System.out.println((i + 1) + ". " + cart.get(i));
}

Or use forEach with a method reference:

cart.forEach(System.out::println);

Removing items while looping

This looks reasonable but throws ConcurrentModificationException:

for (String item : cart) {
    if (item.startsWith("R")) {
        cart.remove(item);    // don't do this
    }
}

The safe, modern way is removeIf:

cart.removeIf(item -> item.startsWith("R"));

Sorting and searching

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

public class SortDemo {
    public static void main(String[] args) {
        List<String> names = new ArrayList<>(List.of("Tunde", "ada", "Chidi", "Bola"));

        Collections.sort(names);                          // natural order (case-sensitive)
        System.out.println(names);                        // [Bola, Chidi, Tunde, ada]

        names.sort(String.CASE_INSENSITIVE_ORDER);
        System.out.println(names);                        // [ada, Bola, Chidi, Tunde]

        names.sort(Comparator.comparing(String::length).reversed());
        System.out.println(names);                        // [Chidi, Tunde, Bola, ada] (stable sort keeps ties in order)

        List<Integer> scores = new ArrayList<>(List.of(72, 91, 58, 85));
        System.out.println(Collections.max(scores));      // 91
        Collections.sort(scores);
        System.out.println(Collections.binarySearch(scores, 85)); // 2
    }
}

binarySearch only works on a sorted list. See our binary search tutorial to learn how it works.

Lists of your own objects

record Student(String name, int score) { }

List<Student> students = new ArrayList<>();
students.add(new Student("Ada", 88));
students.add(new Student("Chidi", 74));
students.add(new Student("Fatima", 93));

students.sort(Comparator.comparingInt(Student::score).reversed());
System.out.println(students.get(0).name()); // Fatima

If you use contains, indexOf or remove(Object) with your own class, make sure it implements equals correctly. Records do this for you.

How ArrayList works inside

An ArrayList keeps its elements in a regular array. When the array fills up, it creates a bigger one (about 1.5 times the size) and copies everything across. This explains its performance:

  • get(i) and set(i, x): very fast, constant time.
  • add(x) at the end: fast on average (amortised constant time).
  • add(0, x) or remove(0): slow for big lists, because every later element has to shift.
  • contains(x) and indexOf(x): linear time, because they check elements one by one.

So if you mostly add to the end and read by index, ArrayList is ideal. If you frequently look up items by value, a HashSet or HashMap is a better fit. LinkedList is rarely faster in practice; ArrayDeque is usually the better choice for queues and stacks.

Converting between arrays and lists

String[] arr = {"a", "b", "c"};
List<String> list = new ArrayList<>(Arrays.asList(arr)); // array -> list
String[] back = list.toArray(new String[0]);              // list -> array

Common mistakes

  • Using List.of and then trying to add to it.
  • Calling get(list.size()), which throws IndexOutOfBoundsException. The last index is size() - 1.
  • Removing elements inside an enhanced for loop instead of using removeIf.
  • Confusing remove(int index) and remove(Object value) on List<Integer>.
  • Using == to compare elements instead of equals.

Summary

  • Declare as List<Type>, create with new ArrayList<>().
  • add, get, set, remove, size, contains cover most daily needs.
  • Use removeIf to delete while iterating, and sort with a Comparator to order items.
  • ArrayList is fast for index access and appending, slow for inserting at the front or searching by value.

Next: store data by key with HashMap in Java.

Ask a question or leave a comment

Your email address will not be published. Required fields are marked *