Java ArrayList tutorial

In this article, we show how to work with ArrayList in Java. Located in the java.util package, ArrayList is an important collection of the Java collections framework.

Java collections framework is a unified architecture for representing and manipulating collections, enabling collections to be manipulated independently of implementation details. A collection is an object that represents a group of objects.

ArrayList is an ordered sequence of elements. It is dynamic and resizable. It provides random access to its elements. Random access means that we can grab any element at constant time. An ArrayList automatically expands as data is added. Unlike simple arrays, an ArrayList can hold data of multiple data types. It permits all elements, including null.

Elements in the ArrayList are accessed via an integer index. Indexes are zero-based. Indexing of elements and insertion and deletion at the end of the ArrayList takes constant time.

An ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. As elements are added to an ArrayList, its capacity grows automatically. Choosing a proper capacity can save some time.

Adding single items

Single elements can be added to an ArrayList with the add() method.

AddingSingleItemsEx.java
package com.zetcode;

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

public class AddingSingleItemsEx {

    public static void main(String[] args) {
        
        List<String> langs = new ArrayList<>();
        
        langs.add("Java");
        langs.add("Python");
        langs.add(1, "C#");
        langs.add(0, "Ruby");
        
        for (String lang : langs) {
            
            System.out.printf("%s ", lang);
        }
        
        System.out.println();
    }
}

The example adds elements to an array list one by one.

List<String> langs = new ArrayList<>();

An ArrayList is created. The data type specified inside the diamond brackets (< >) restricts the elements to this data type; in our case, we have a list of strings.

langs.add("Java");

An element is appended at the end of the list with the add() method.

langs.add(1, "C#");

This time the overloaded add() method inserts the element at the specified position; The "C#" string will be located at the second position of the list; remember, the ArrayList is an ordered sequence of elements.

for (String lang : langs) {
    
    System.out.printf("%s ", lang);
}

With the for loop, we go through the ArrayList list and print its elements.

Ruby Java C# Python 

This is the output. Note that the elements keep the order they were inserted.

The get() and size() methods

The get() returns the element at the specified position in this list and the size() returns the size of the list.

GetAndSizeEx.java
package com.zetcode;

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

public class GetAndSizeEx {

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

        colours.add("blue");
        colours.add("orange");
        colours.add("red");
        colours.add("green");
        
        String col = colours.get(1);
        System.out.println(col);
        
        int size = colours.size();
        
        System.out.printf("The size of the ArrayList is: %d%n", size  );
    }
}

The example uses the get() and size() methods of the ArrayList

String col = colours.get(1);

The get() method returns the second element, which is "orange".

int size = colours.size();

The size() method determines the size of our colours list; we have four elements.

orange
The size of the ArrayList is: 4

This is the output of the example.

Various data types

An ArrayList can contain various data types.

DataTypesEx.java
package com.zetcode;

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

class Base {}

enum Level {
    
    EASY,
    MEDIUM,
    HARD
}

public class DataTypesEx {

    public static void main(String[] args) {

        Level level = Level.EASY;
        
        List da = new ArrayList();
        
        da.add("Java");
        da.add(3.5);
        da.add(55);
        da.add(new Base());
        da.add(level);

        for (Object el : da) {

            System.out.println(el);
        }
    }

}

The example adds five different data types into an array list — a string, double, integer, object, and enumeration.

List da = new ArrayList();

When we add multiple data types to a list, we omit the angle brackets.

Java
3.5
55
com.zetcode.Base@659e0bfd
EASY

This is the output.

Adding multiple elements

The following example uses the addAll() method to add multiple elements to a list in one step.

AddingMultipleItemsEx.java
package com.zetcode;

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

public class AddingMultipleItemsEx {

    public static void main(String[] args) {
        
        List<String> colours1 = new ArrayList<>();
        
        colours1.add("blue");
        colours1.add("red");
        colours1.add("green");
        
        List<String> colours2 = new ArrayList<>();
        
        colours2.add("yellow");
        colours2.add("pink");
        colours2.add("brown");        

        List<String> colours3 = new ArrayList<>();
        colours3.add("white");
        colours3.add("orange");
        
        colours3.addAll(colours1);
        colours3.addAll(2, colours2);

        for (String col : colours3) {
            
            System.out.println(col);
        }
    }
}

Two lists are created. Later, the elements of the lists are added to the third list with the addAll() method.

colours3.addAll(colours1);

The addAll() method adds all of the elements to the end of the list.

colours3.addAll(2, colours2);

This overloaded method adds all of the elements starting at the specified position.

white
orange
yellow
pink
brown
blue
red
green

This is the output of the example.

Modifying list

The next example uses methods to modify the ArrayList.

ModifyingListEx.java
package com.zetcode;

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

public class ModifyingListEx {

    public static void main(String[] args) {

        List<String> items = new ArrayList<>();
        fillList(items);

        items.set(3, "watch");
        items.add("bowl");
        items.remove(0);
        items.remove("pen");

        for (Object el : items) {

            System.out.println(el);
        }
        
        items.clear();
        
        if (items.isEmpty()) {
            
            System.out.println("The list is empty");
        } else {
            System.out.println("The list is not empty");
        }
    }

    public static void fillList(List<String> list) {

        list.add("coin");
        list.add("pen");
        list.add("pencil");
        list.add("clock");
        list.add("book");
        list.add("spectacles");
        list.add("glass");
    }
}

An ArrayList is created and modified with the set(), add(), remove(), and clear() methods.

items.set(3, "watch");

The set() method replaces the fourth element with the "watch" item.

items.add("bowl");

The add() method adds a new element at the end of the list.

items.remove(0);

The remove() method removes the first element, having index 0.

items.remove("pen");

The overloaded remove() method remove the first occurrence of the "pen" item.

items.clear();

The clear() method removes all elements from the list.

if (items.isEmpty()) {

The isEmpty() method determines if the list is empty.

pencil
watch
book
spectacles
glass
bowl
The list is empty

This is the output of the example.

The removeIf() method

The removeIf() method removes all of the elements of a collection that satisfy the given predicate.

RemoveIfEx.java
package com.zetcode;

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

public class RemoveIfEx {

    public static void main(String[] args) {
        
        List<Integer> values = new ArrayList<>();
        values.add(5);
        values.add(-3);
        values.add(2);
        values.add(8);
        values.add(-2);
        values.add(6);

        values.removeIf(val -> val < 0);
        
        System.out.println(values);
    }
}

In our example, we have an ArrayList of integers. We use the removeIf method to delete all negative values.

values.removeIf(val -> val < 0);

All negative numbers are removed from the array list.

[5, 2, 8, 6]

This is the output.

The replaceAll() method

The replaceAll() method replaces each element of a list with the result of applying the operator to that element.

ReplaceAllEx.java
package com.zetcode;

import java.util.ArrayList;
import java.util.List;
import java.util.function.UnaryOperator;

public class ReplaceAllEx {

    public static void main(String[] args) {
        
        List<String> items = new ArrayList<>();
        items.add("coin");
        items.add("pen");
        items.add("cup");
        items.add("notebook");
        items.add("class");
                
        UnaryOperator<String> uo = (x) -> x.toUpperCase();
        
        items.replaceAll(uo);
        
        System.out.println(items);
    }
}

The example applies an operator on each of the list elements; the elements' letters are transformed to uppercase.

UnaryOperator<String> uo = (x) -> x.toUpperCase();

A UnaryOperator that transforms letters to uppercase is created.

items.replaceAll(uo);

The operator is applied on the list elements with the replaceAll() method.

[COIN, PEN, CUP, NOTEBOOK, CLASS]

This is the output.

The second example uses the replaceAll() method to capitalize string items.

ReplaceAllEx2.java
package com.zetcode;

import java.util.ArrayList;
import java.util.List;
import java.util.function.UnaryOperator;

class MyOperator<T> implements UnaryOperator<String> {

    @Override
    public String apply(String var) {

        if (var == null || var.length() == 0) {
            return var;
        }
        return var.substring(0, 1).toUpperCase() + var.substring(1);
    }
}

public class ReplaceAllEx2 {

    public static void main(String[] args) {

        List<String> items = new ArrayList<>();

        items.add("coin");
        items.add("pen");
        items.add("cup");
        items.add("notebook");
        items.add("glass");

        items.replaceAll(new MyOperator<>());

        System.out.println(items);
    }
}

We have a list of string items. These items are capitalized with the help of the replaceAll() method.

class MyOperator<T> implements UnaryOperator<String> {

A custom UnaryOperator is created.

@Override
public String apply(String var) {

    if (var == null || var.length() == 0) {
        return var;
    }
    return var.substring(0, 1).toUpperCase() + var.substring(1);
}

Inside the UnaryOperator's apply() method, we retur the string with its first letter in uppercase.

items.replaceAll(new MyOperator<>());

The operator is applied on the list items.

[Coin, Pen, Cup, Notebook, Glass]

This is the output of the example.

The contains() method

The contains() method returns true if a list contains the specified element.

ReplaceAllEx.java
package com.zetcode;

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

public class CheckingItemEx {

    public static void main(String[] args) {
        
        List<String> items = new ArrayList<>();
        
        items.add("coin");
        items.add("pen");
        items.add("cup");
        items.add("notebook");
        items.add("class");
        
        String item = "pen";
        
        if (items.contains(item)) {
            
            System.out.printf("There is a %s in the list%n", item);
        }
    }
}

The example checks if the specified item is in the list.

if (items.contains(item)) {
    
    System.out.printf("There is a %s in the list%n", item);
}

The message is printed if the item is in the list.

There is a pen in the list

This is the output.

Getting index of elements

Each of the elements in an ArrayList has its own index number. The indexOf() returns the index of the first occurrence of the specified element, or -1 if the list does not contain the element. The lasindexOf() returns the index of the last occurrence of the specified element, or -1 if the list does not contain the element.

GetIndexEx.java
package com.zetcode;

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

public class GetIndexEx {

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

        colours.add(0, "blue");
        colours.add(1, "orange");
        colours.add(2, "red");
        colours.add(3, "green");
        colours.add(4, "orange");
        
        int idx1 = colours.indexOf("orange");
        System.out.println(idx1);
        
        int idx2 = colours.lastIndexOf("orange");
        System.out.println(idx2);        
    }
}

The example prints the first and last index of the "orange" element.

1
4

This is the example output.

The subList() method

The subList() method returns a view of the portion of a list between the specified fromIndex, inclusive, and toIndex, exclusive. The changes in a sublist are reflected in the original list.

SubListEx.java
package com.zetcode;

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

public class SubListEx {

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

        items.add("coin");
        items.add("pen");
        items.add("cup");
        items.add("notebook");
        items.add("glass");
        items.add("chair");
        items.add("ball");
        items.add("bowl");
        
        List<String> items2 = items.subList(2, 5);
        
        System.out.println(items2);
        
        items2.set(0, "bottle");
        
        System.out.println(items2);
        System.out.println(items);
    }
}

The example creates a sublist from a list of items.

List<String> items2 = items.subList(2, 5);

A sublist is created with the subList() method; it contains items with indexes 2, 3, and 4.

items2.set(0, "bottle");

We replace the first item of the sublist; the modification is reflected in the original list, too.

[cup, notebook, glass]
[bottle, notebook, glass]
[coin, pen, bottle, notebook, glass, chair, ball, bowl]

This is the output of the example.

Traversing ArrayList

In the following example, we show five ways to traverse an ArrayList.

TraversingArrayListEx.java
package com.zetcode;

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

public class TraversingArrayListEx {

    public static void main(String[] args) {

        List<Integer> nums = new ArrayList<>();
        nums.add(2);
        nums.add(6);
        nums.add(7);
        nums.add(3);
        nums.add(1);
        nums.add(8);

        for (int i = 0; i < nums.size(); i++) {

            System.out.printf("%d ", nums.get(i));
        }

        System.out.println();

        for (int num : nums) {

            System.out.printf("%d ", num);
        }

        System.out.println();

        int j = 0;
        while (j < nums.size()) {

            System.out.printf("%d ", nums.get(j));
            j++;
        }

        System.out.println();
        
        ListIterator<Integer> it = nums.listIterator();
        
        while(it.hasNext()) {
            
            System.out.printf("%d ", it.next());
        }
        
        System.out.println();

        nums.forEach(e -> System.out.printf("%d ", e));
        System.out.println();
    }
}

In the example, we traverse an array list of integers with for loops, while loop, iterator, and forEach() construct.

List<Integer> nums = new ArrayList<>();
nums.add(2);
nums.add(6);
nums.add(7);
nums.add(3);
nums.add(1);
nums.add(8);

We have created an ArrayList of integers.

for (int i = 0; i < nums.size(); i++) {

    System.out.printf("%d ", nums.get(i));
}

Here, we use the classic for loop to iterate over the list.

for (int num : nums) {

    System.out.printf("%d ", num);
}

The second way uses the enhanced-for loop, which was introduced int Java 5.

int j = 0;
while (j < nums.size()) {

    System.out.printf("%d ", nums.get(j));
    j++;
}

The third way uses the while loop.

ListIterator<Integer> it = nums.listIterator();

while(it.hasNext()) {
    
    System.out.printf("%d ", it.next());
}

Here, a ListIterator is used to traverse the list.

nums.forEach(e -> System.out.printf("%d ", e));

In the last way, we use the forEach() method, which was introduced in Java 8.

2 6 7 3 1 8 
2 6 7 3 1 8 
2 6 7 3 1 8 
2 6 7 3 1 8 
2 6 7 3 1 8 

The example prints the elements of a list to the console, utilizing various techniques.

Sorting ArrayList

The sort() method sorts a list according to the order induced by the specified comparator.

ArrayListSortingEx.java
package com.zetcode;

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

class Person {
    
    private int age;
    private String name;

    public Person(int age, String name) {
        
        this.age = age;
        this.name = name;
    }
    
    public int getAge() {
        
        return age;
    }
    
    @Override
    public String toString() {
        return "Age: " + age + " Name: " + name;
    }
}

public class ArrayListSortingEx {
    
    public static void main(String[] args) {
        
        List<Person> persons = createList();
        
        persons.sort(Comparator.comparing(Person::getAge).reversed());
        
        System.out.println(persons);
        
    }
    
    private static List<Person> createList() {
        
        List<Person> persons = new ArrayList<>();
        
        persons.add(new Person(17, "Jane"));
        persons.add(new Person(32, "Peter"));
        persons.add(new Person(47, "Patrick"));
        persons.add(new Person(22, "Mary"));
        persons.add(new Person(39, "Robert"));
        persons.add(new Person(54, "Greg"));    
        
        return persons;
    }
}

We have an ArrayList of custom Person classes. We sort the persons according to their age in a reversed order.

persons.sort(Comparator.comparing(Person::getAge).reversed());

This line sorts the persons by their age, from the oldest to the youngest.

[Age: 54 Name: Greg, Age: 47 Name: Patrick, Age: 39 Name: Robert, Age: 32 Name: Peter, 
    Age: 22 Name: Mary, Age: 17 Name: Jane]

This is the output.

Working with ArrayList and simple Java array

The following example uses an ArrayList with a simple Java array.

ArrayEx.java
package com.zetcode;

import java.util.Arrays;
import java.util.List;

public class ArrayEx {

    public static void main(String[] args) {
        
        List<String> planets = Arrays.asList("Mercury", "Venus", "Earth", 
                "Mars", "Jupiter", "Saturn", "Uranus", "Neptune");

        for (String planet : planets) {

            System.out.println(planet);
        }        
        
        System.out.println("***************");
        
        String[] planets2 = planets.toArray(new String[planets.size()]);
        
        for (String planet : planets2) {
            
            System.out.println(planet);
        }
    }
}

An ArrayList is converted to an array and vice versa.

List<String> planets = Arrays.asList("Mercury", "Venus", "Earth", 
        "Mars", "Jupiter", "Saturn", "Uranus", "Neptune");

With the Arrays.asList() method, we create a fixed-size list backed by the specified array.

String[] planets2 = planets.toArray(new String[planets.size()]);

The ArrayList's toArray() is used to convert a list to an array.

In this article, we have work with the Java ArrayList container.

You might also be interested in the following related tutorials: Java tutorial, Introduction to Google Guava, Filtering a list in Java, or Reading a web page in Java.