Java ArrayList Collection Tutorial

In this Java tutorial we learn about the ordered ArrayList collection that we can use to create resizable arrays of a single type.

We learn about the required package to be imported, how to create, retrieve, mutate and delete elements as well as how to initialize an ArrayList with values.

We also discuss other ArrayList methods that provide common functionality, and how to convert Arrays to ArrayLists and vice versa.

Here's a table of contents of what you'll learn in this lesson:
(click on a link to skip to its section)

Let's jump right in.

What is an ArrayList Collection

An ArrayList is an ordered collection, similar to an array, that allows us to create resizable arrays of a single type.

An ArrayList can automatically adjust its capacity when we add or remove elements from it. ArrayLists are also known as dynamic arrays.

The ArrayList class is an implementation of the List interface that extends the Collection interface.

The ArrayList package

Before we can work with ArrayLists, we need to import its package.

Example:
 import java.util.ArrayList;

Without the package, the compiler will raise an error when we try to instantiate a new ArrayList.

How to instantiate an ArrayList in Java

An ArrayList is a generic. We instantiate an ArrayList the same way we do a generic class with a single generic type.

Syntax:
ArrayList<type_class> name = new ArrayList<type_class>();

// or we can omit the second type
ArrayList<type_class> name = new ArrayList<>();

As with any other generic, we specify the type class wrapper instead of the primitive type. For example, we use Integer , not int .

Example:
// import appropriate package
import java.util.ArrayList;

public class Program {
    public static void main(String[] args) {

        // instantiate new empty ArrayList
        ArrayList<String> employee = new ArrayList<>();
    }
}

In the example above, we instantiate a new ArrayList object called ‘employee’.

How to add elements to an ArrayList in Java

To add elements to an ArrayList, we use the .add() method on the object. The method takes the value we want to add as an argument.

Syntax:
 arraylist_name.add(value);

The value’s type must match the type we specified in the object instantiation.

Example:
// import appropriate package
import java.util.ArrayList;

public class Program {
    public static void main(String[] args) {

        // instantiate new empty ArrayList
        ArrayList<String> employee = new ArrayList<>();

        // add elements
        employee.add("John");
        employee.add("Jane");
        employee.add("Jack");
        employee.add("Jill");

        System.out.println(employee);
    }
}

In the example above, we add 4 string elements to the ArrayList.

We can also add the values with an index number. We separate the index and value with a comma.

Example:
// import appropriate package
import java.util.ArrayList;

public class Program {
    public static void main(String[] args) {

        // instantiate new empty ArrayList
        ArrayList<String> employee = new ArrayList<>();

        // add elements
        employee.add(0, "John");
        employee.add(1, "Jane");
        employee.add(2, "Jack");
        employee.add(3, "Jill");

        System.out.println(employee);
    }
}

How to add the elements of one ArrayList to another in Java

We can add all the elements from one ArrayList to another with the .addAll() method. The method takes an ArrayList object as an argument.

Syntax:
ArrayList<type_class> name1 = new ArrayList<>();
ArrayList<type_class> name2 = new ArrayList<>();

// add all elements from name2 to name1
name1.addAll( name2 );
Example:
// import appropriate package
import java.util.ArrayList;

public class Program {
    public static void main(String[] args) {

        ArrayList<String> animal = new ArrayList<>();
        animal.add("Crocodile");

        System.out.println("Animal list: " + animal);

        ArrayList<String> mammal = new ArrayList<>();
        mammal.add("Elephant");
        mammal.add("Dog");

        System.out.println("Mammal list: " + mammal);

        // add all the elements from
        // 'mammal' to 'animal'
        animal.addAll(mammal);

        System.out.println("New animal list: " + animal);
    }
}

In the example above, we add all the elements from the ‘mammal’ ArrayList to the ‘animal’ ArrayList.

How to initialize an ArrayList with values in Java

If we know the values we want to add to the list beforehand, we can initialize the ArrayList by calling the static Arrays.asList() method in the ArrayList constructor.

We also need to import the ‘Arrays’ package to be able to use the asList method.

Syntax:
// import package
import java.util.Arrays;

// initialize ArrayList with Arrays.asList()
ArrayList<type_class> name = new ArrayList<>( Arrays.asList(value1, value2, ...) );
Example:
import java.util.ArrayList;
import java.util.Arrays;

public class Program {
    public static void main(String[] args) {

        // initialize a new Arraylist
        // with values by using the
        // constructor and Array.asList()
        ArrayList<String> employee = new ArrayList<>( Arrays.asList("John", "Jane", "Jack", "Jill") );

        System.out.println(employee);
    }
}

If you want to learn more about initializing an ArrayList in one line, see this question from StackOverflowOpens up in a new page .

How to access single ArrayList elements in Java

To access single elements in an ArrayList we use the .get() method. The method takes the index number of the element we want to access as an argument.

Syntax:
 arraylist_name.get(0);

An ArrayList numerical index starts at 0.

Example:
import java.util.ArrayList;
import java.util.Arrays;

public class Program {
    public static void main(String[] args) {

        // initialize a new Arraylist
        ArrayList<String> employee = new ArrayList<>( Arrays.asList("John", "Jane", "Jack", "Jill") );

        // get second element
        System.out.println( employee.get(1) );
    }
}

In the example above, we specify the index number as 1 to get the second element in the ArrayList.

How to access ArrayList elements with a loop in Java

To access elements in an ArrayList in a loop, we use the foreach (enhanced for) loopOpens up in a new page .

Example:
import java.util.ArrayList;
import java.util.Arrays;

public class Program {
    public static void main(String[] args) {

        // initialize a new Arraylist
        ArrayList<String> employee = new ArrayList<>( Arrays.asList("John", "Jane", "Jack", "Jill") );

        // loop through the ArrayList
        // storing the element value on
        // each iteration in 'i'
        for (String i : employee) {

            System.out.println(i);
        }
    }
}

In the example above, we iterate through the ArrayList with an enhanced for loop and print the element on each iteration.

How to change ArrayList elements in Java

ArrayList elements in Java are mutable, which means we can change them at runtime.

To change an element, we use the .set() method. The method takes two arguments, the index number and the new value.

Syntax:
 arraylist_name.set(index, new_value);
Example:
import java.util.ArrayList;
import java.util.Arrays;

public class Program {
    public static void main(String[] args) {

        // initialize a new Arraylist
        ArrayList<String> employee = new ArrayList<>( Arrays.asList("John", "Jane", "Jack", "Jill") );

        System.out.println(employee);

        // mutate second element
        employee.set(1, "Jane Doe");

        System.out.println(employee);
    }
}

In the example above, we change the value of the second element from ‘Jane’ to ‘Jane Doe’.

How to remove single ArrayList elements in Java

To remove a single element from an ArrayList, we use the .remove() method. The method takes the index number of the element to be removed as an argument.

Syntax:
 arraylist_name.remove(index);
Example:
import java.util.ArrayList;
import java.util.Arrays;

public class Program {
    public static void main(String[] args) {

        // initialize a new Arraylist
        ArrayList<String> employee = new ArrayList<>( Arrays.asList("John", "Jane", "Jack", "Jill") );

        System.out.println(employee);

        // remove third element
        employee.remove(2);

        System.out.println(employee);
    }
}

In the example above, we remove the third element (Jack) from the ArrayList.

How to remove all ArrayList elements in Java

To remove all the elements from an ArrayList at once, we use the .removeAll() method. The method takes the arraylist_name as an argument.

Syntax:
 arraylist_name.removeAll(arraylist_name);
Example:
import java.util.ArrayList;
import java.util.Arrays;

public class Program {
    public static void main(String[] args) {

        // initialize a new Arraylist
        ArrayList<String> employee = new ArrayList<>( Arrays.asList("John", "Jane", "Jack", "Jill") );

        System.out.println(employee);

        // remove all elements
        employee.removeAll(employee);

        System.out.println(employee);
    }
}

Alternatively, we can use the .clear() method, which takes no arguments.

Syntax:
 arraylist_name.clear();
Example:
import java.util.ArrayList;
import java.util.Arrays;

public class Program {
    public static void main(String[] args) {

        // initialize a new Arraylist
        ArrayList<String> employee = new ArrayList<>( Arrays.asList("John", "Jane", "Jack", "Jill") );

        System.out.println(employee);

        // remove all elements
        employee.clear();

        System.out.println(employee);
    }
}

In both situations the ArrayList is cleared. It still exists, its just empty afterwards.

The clear method is more efficient than the removeAll method.

How to get the ArrayList length (size) in Java

Java provides us with the .size() method to retrieve the number of elements in the ArrayList. The method takes no arguments.

Syntax:
 arraylist_name.size();
Example:
import java.util.ArrayList;
import java.util.Arrays;

public class Program {
    public static void main(String[] args) {

        // initialize a new Arraylist
        ArrayList<String> employee = new ArrayList<>( Arrays.asList("John", "Jane", "Jack", "Jill") );

        System.out.println("ArrayList size: " + employee.size());

        for (byte i = 0; i < employee.size(); i++) {

            System.out.println(employee.get(i));
        }
    }
}

In the example above, we use the ArrayList size to loop through it with a standard for loop.

How to convert an ArrayList into an Array in Java

In Java we can convert an ArrayList into an Array with the .toArray() method. The method takes the name of the array we’re converting to as an argument.

The array must be of the same type as the ArrayList.

Syntax:
 arraylist_name.toArray(array_name);
Example:
import java.util.ArrayList;
import java.util.Arrays;

public class Program {
    public static void main(String[] args) {

        // initialize a new Arraylist
        ArrayList<String> employee = new ArrayList<>( Arrays.asList("John", "Jane", "Jack", "Jill") );
        System.out.println("ArrayList: " + employee);

        // array to convert to
        String[] empArray = new String[employee.size()];

        // convert
        employee.toArray(empArray);

        System.out.print("Array: ");
        for (String i : empArray) {
            System.out.print(i + " ");
        }
    }
}

In the example above, we convert the ‘employee’ ArrayList to the ‘empArray’ array.

How to convert an Array into an ArrayList in Java

Java also allows us to convert a regular Array into an ArrayList with the .asList() method in the ArrayList constructor. The method takes the name of the array we want to convert from as an argument.

To use the method, we need to import the ‘Arrays’ package.

Syntax:
// import package
import java.util.Arrays;

// convert array to ArrayList
ArrayList<type_class> arraylist_name = new ArrayList<>(Arrays.asList(array_name));

Technically, we’re not converting an array to an ArrayList so much as creating a new ArrayList and then copying the values into it.

Example:
import java.util.ArrayList;
import java.util.Arrays;

public class Program {
    public static void main(String[] args) {

        // initialize an array
        String[] empArray = { "John", "Jane", "Jack", "Jill" };

        // initialize an ArrayList and
        // copy the values from the array
        ArrayList<String> employee = new ArrayList<>( Arrays.asList(empArray) );

        System.out.println("ArrayList: " + employee);
    }
}

In the example above, we create a new ArrayList and copy the values from the array over to it.

List of common ArrayList methods

Following is a list of more methods commonly used with ArrayLists.

MethodDescription
clone()Create a new ArrayList with the same element, size, and capacity
contains()Search the ArrayList for a specified element and returns a boolean
ensureCapacity()Specifies the amount of elements the ArrayList can contain
isEmpty()Checks if the ArrayList is empty
indexOf()Find a specified element in the ArrayList and return its index, if it exists
toString()Converts the whole ArrayList to a single string
trimToSize()Reduces the size of the ArrayList

Summary: Points to remember

  • An ArrayList is a generic collection that allows us to create resizable collections of a single type.
  • An ArrayList requires the java.util.ArrayList package to be imported before we can use it.
  • An ArrayList must be instantiated into an object and accepts its type as a generic argument between angle brackets.
  • We can add, retrieve, mutate and remove elements from the ArrayList with the appropriate methods.
  • To initialize an ArrayList with values, we use the Arrays.asList method with values as arguments in the ArrayList constructor.
  • The clear and removeAll methods both remove all the elements from the ArrayList, however the clear method is more efficient.
  • To get the length of an ArrayList, we use the size method.
  • ArrayLists can be converted into standard arrays, and vice versa.