ArrayList in Java with Examples

Feb 21, 2020 · 6 mins read

ArrayList class is part of the Java Collections Framework. It implements the List interface and adds support for resizable arrays that can grow and shrink as elements are added and removed. In computer science, these are also known as ‘dynamic arrays’.

In contrast, standard arrays in Java e.g. int [] are fixed size, always occupying a fixed amount of memory. You must assign them a capacity during initialization. When standard arrays become full, they cannot be adjusted to make room for more elements. You must know in advance how many elements the array will hold and initialize accordingly. ArrayList objects have no such limitation. You can create them by providing an initial size and they will grow or shrink automatically. Just like arrays, ArrayList objects allow random access allowing any item in the array to be accessed in constant time.

Let’s take a look at some examples.

Create an ArrayList and add elements to it

In the first example, we’ll create an ArrayList object and treat it like a standard array to illustrate the similarities. Please note that we don’t specify a size or capacity when creating the ArrayList. By default, initial capacity is set to 10, if you don’t specify it.

import java.util.ArrayList;

public class ArrayListExample {

    public static void main(String[] args) {

        // Creating an array size with no initial capacity
        ArrayList<Integer> arrayList = new ArrayList<>();

        // Insert 10 elements into the list
        // Each element is loop index i + 100 eg 100 thru 109
        for (int i=0; i<10; i++) {
            arrayList.add(i, i+100);
        }

        // Print elements using for loop like standard arrays
        for (int i=0; i<10; i++) {
            System.out.println(arrayList.get(i));
        }

        // Let's change the item at 2nd position
        arrayList.set(1, 333);

        System.out.println("after change");
        System.out.println("Item at 2nd position i.e. arrayList[1]: " 
                + arrayList.get(1));
    }
}

Output

100
101
102
103
104
105
106
107
108
109
after change
Item at 2nd position i.e. arrayList[1]: 333

Removing elements from ArrayList

Deleting elements from regular arrays at specific positions isn’t straighforward and requires a lot of work. When you delete an element, you’d either leave a hole (null or 0 etc.) at the position or have to shift subsequent elements to the left manually. ArrayList.remove(int index) not only removes the element at the specified index but also shifts all subsequent elements to the left. Let’s take a look at an example.

import java.util.ArrayList;

public class ArrayListExample2 {

    public static void main(String[] args) {

        // Creating an array list
        ArrayList<String> arrayList = new ArrayList<>();

        // Insert some elements to the end of the list
        arrayList.add("java");
        arrayList.add("rust");
        arrayList.add("go");
        arrayList.add("python");

        for (int i=0; i<arrayList.size(); i++) {
            System.out.println(s);
        }

        // Remove 'go'
        arrayList.remove(2);

        System.out.println("== after remove(2)==");

        for (int i=0; i<arrayList.size(); i++) {
            System.out.println("index = " + i
                    + ", item: " + arrayList.get(i));
        }
    }
}

Output

java
rust
go
python
== after remove(2)==
index = 0, item: java
index = 1, item: rust
index = 2, item: python

Iterating over ArrayList elements

In the next example, we’ll use different strategies of iterating over an ArrayList. These methods are not specific to ArrayList class and are available for all classes that extend the List interface.

  1. Using the standard for loop
  2. Using for-each construct
  3. Using ArrayList.forEach(…) and Consumer interface
  4. Using ArrayList.forEach(...) and Lambda expression
  5. Using ArrayList.forEach(...) and method reference

import java.util.ArrayList;
import java.util.function.Consumer;

public class ArrayListExample3 {

    public static void main(String[] args) {

        // Creating an array list
        ArrayList<Integer> numbers = new ArrayList<>();

        // Insert some elements
        numbers.add(1);
        numbers.add(2);
        numbers.add(3);

        // Iterate using standard for loop
        for (int i=0; i<numbers.size(); i++) {
            System.out.println(i);
        }
        
        // Iterate using an iterator
        for (Integer num: numbers) {
            System.out.println(num);
        }
        
        // Iterate using ArrayList.forEach
        numbers.forEach(new Consumer<Integer>() {
            @Override
            public void accept(Integer num) {
                System.out.println(num);
            }
        });
        
        // Iterate using forEach and Lambda
        numbers.forEach(num -> System.out.println(num));

        // Iterate using forEach and method reference
        numbers.forEach(System.out::println);
    }
}

Other notes:

  • Under the hood, ArrayList uses standard arrays to store elements. If you’re interested, you can see the source here.
  • ArrayList class is not synchronized and hence it is not safe for multithreading. Access to it by multiple threads must be synchronized. You can also use the Collections.synchronizedList method.
  • ArrayList allows null and duplicate values.

Here’s a cheat sheet I created highlighting important methods of the ArrayList class.

arraylist-cheat-sheet

That’s all. I hope you enjoyed it. Please leave comments below if you have a question or even just a comment. Thanks for reading.



Join Newsletter
Enter your email address to receive a very occasional newsletter. I'll never spam or sell your email.