Java ArrayList

An ArrayList is a list which can grow and shrink, unlike an array which has a fixed size. It is part of the Collections framework in java.util.

Create and use

import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        ArrayList<String> names = new ArrayList<>();   // the type goes in <>

        names.add("Riya");
        names.add("Aman");
        names.add("Meera");
        names.add(1, "Karan");          // add at a position

        System.out.println(names);
        System.out.println(names.get(2));
        System.out.println(names.size());

        names.set(0, "Riya S");         // change an item
        names.remove("Aman");           // remove by value
        names.remove(0);                // remove by index
        System.out.println(names);
        System.out.println(names.contains("Meera"));
        System.out.println(names.indexOf("Meera"));
        System.out.println(names.isEmpty());
    }
}
Output

[Riya, Karan, Aman, Meera]
Aman
4
[Karan, Meera]
true
1
false

Loop through a list

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

public class Loop {
    public static void main(String[] args) {
        List<Integer> marks = new ArrayList<>();
        marks.add(70);
        marks.add(85);
        marks.add(90);

        for (int m : marks) {
            System.out.print(m + " ");
        }
        System.out.println();

        for (int i = 0; i < marks.size(); i++) {
            System.out.println(i + " -> " + marks.get(i));
        }

        marks.forEach(m -> System.out.print(m * 2 + " "));
        System.out.println();
    }
}
Output

70 85 90
0 -> 70
1 -> 85
2 -> 90
140 170 180

We wrote List<Integer> marks = new ArrayList<>(). It is a good habit to use the interface (List) as the variable type.

Only objects, not primitives

A list can not hold int, only Integer. Java converts between them automatically (autoboxing).

Sort and other helpers

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

public class Sort {
    public static void main(String[] args) {
        List<String> fruits = new ArrayList<>(List.of("mango", "apple", "banana", "cherry"));

        Collections.sort(fruits);
        System.out.println(fruits);
        Collections.reverse(fruits);
        System.out.println(fruits);

        fruits.sort(Comparator.comparing(String::length).thenComparing(Comparator.naturalOrder()));
        System.out.println(fruits);

        System.out.println(Collections.max(fruits));
        System.out.println(fruits.subList(1, 3));
    }
}
Output

[apple, banana, cherry, mango]
[mango, cherry, banana, apple]
[apple, mango, banana, cherry]
mango
[mango, banana]

A common beginner error is to use Comparator without the import. Java tells exactly what is missing:

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

public class Sort2 {
    public static void main(String[] args) {
        List<String> fruits = new ArrayList<>(List.of("b", "a"));
        fruits.sort(Comparator.naturalOrder());
    }
}
Output

Sort2.java:7: error: cannot find symbol
fruits.sort(Comparator.naturalOrder());
^
symbol: variable Comparator
location: class Sort2
1 error
error: compilation failed

Remove while looping

Removing items inside a for each loop throws a ConcurrentModificationException. Use removeIf:

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

public class Remove {
    public static void main(String[] args) {
        List<Integer> numbers = new ArrayList<>(List.of(1, 2, 3, 4, 5, 6));
        numbers.removeIf(n -> n % 2 == 0);
        System.out.println(numbers);

        List<Integer> copy = new ArrayList<>(List.of(1, 2, 3, 4));
        try {
            for (Integer n : copy) {
                if (n == 1) copy.remove(n);        // removing inside the loop
            }
        } catch (java.util.ConcurrentModificationException e) {
            System.out.println("ConcurrentModificationException");
        }
    }
}
Output

[1, 3, 5]
ConcurrentModificationException

Immutable lists

import java.util.List;

public class Immutable {
    public static void main(String[] args) {
        List<String> fixed = List.of("a", "b", "c");
        System.out.println(fixed);
        fixed.add("d");
    }
}
Output

[a, b, c]
Exception in thread "main" java.lang.UnsupportedOperationException
at java.base/java.util.ImmutableCollections.uoe(ImmutableCollections.java:159)
at java.base/java.util.ImmutableCollections$AbstractImmutableCollection.add(ImmutableCollections.java:164)
at Immutable.main(Immutable.java:7)

ArrayList or array?

PointArrayArrayList
SizeFixedGrows and shrinks
TypesPrimitives and objectsObjects only
SpeedA little fasterVery fast, with more helper methods
Note: Use ArrayList as the default list. Choose LinkedList only when you add and remove at the start a lot. Next: Java HashMap.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
Sort a list of students with a Comparator
Count the frequency of words with a HashMap
Remove duplicates from a list and keep the order
Interview Questions & Answers
What is the difference between an array and an ArrayList in Java?
How does HashMap work internally in Java?
What is the difference between HashMap, Hashtable and ConcurrentHashMap?
Why must you override both equals() and hashCode() in Java?
What is the difference between Comparable and Comparator in Java?
What is the difference between ArrayList and LinkedList in Java?
What is the difference between fail-fast and fail-safe iterators?