ArrayList in Java with Examples (2020)

Feb 21, 2020 · 11 mins read

ArrayList Overview

ArrayList class is part of the Java Collections Framework. It is used for storing a dynamically sized, ordered collection of elements. As elements are added and removed, it grows or shrinks its size automatically. 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.

ArrayList implements the List interface. Internally, ArrayList class uses plain old arrays to store a collection of elements, hence the name ArrayList. As elements are added, this class grows the capacity of the internal array by allocating a larger array and moving existing elements to it. Likewise, when elements are removed and extra space isn’t needed, it shrinks the internal array. This is similar to that of dynamic arrays’ in other programming languages.

Elements are stored in order and can be retrieved by index, just like arrays.

Let’s take a look at some examples.

  1. ArrayList Overview
  2. ArrayList Operations
  3. Examples
    1. Creating & Adding Elements to ArrayList
    2. Removing Elements from ArrayList
    3. Iterating over ArrayList Elements
    4. Searching for Elements in ArrayList
  4. ArrayList Properties
    1. Multithreading
    2. Null and Duplicate Values
    3. ArrayList Sorting
  5. Cheat Sheet

ArrayList Operations

Here are few notable operations of the ArrayList class which we’ll exlore in this tutorial.

  • add(element) to add a new element to the end of this list or add(index, element) to add element at the specified index.
  • addAll(collection) to append another collection (e.g. another ArrayList) to it.
  • set(index, element) replaces the element at the specified position in this list with the specified element.
  • get(index) to get an element at the index.
  • isEmpty() to check if there are any elements in this list. Returns true if this list contains no elements.
  • size() returns the number of elements in this list.
  • clear() to delete all elements. You can also use removeAll() to achieve the same, but it is slower than clear().
  • remove(index) removes the element at the index in this list. Shifts any subsequent elements to the left (subtracts one from their indices).
  • remove(object) removes the first occurrence of the specified element from this list.
  • removeIf(predicate) removes element from the ArrayList that satisfy the predicate argument e.g. removeIf(s -> s.length == 3)
  • contains(object), indexOf(object) and lastIndexOf(object) methods are used for searching for elements in ArrayList.
  • listIterator() to get an ordered list iterator over the elements in this list.
  • toArray() converts this ArrayList into an array.

Examples

Creating & Adding Elements to ArrayList

In the first example, we’ll see how to:

  • 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.
  • add elements to ArrayList using the add(index, element) method.
  • get elements from ArrayList using the get(index) method.
  • set elements at a specific index using the set(index) method.
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 and insert some elements
        ArrayList<String> numbers = new ArrayList<>();
        numbers.add("ArrayList");
        numbers.add("Java");
        numbers.add("Arrays");
        numbers.add("List");
        numbers.add("Collections");

        System.out.println("original => "+ numbers);

        // Remove element at index 1
        numbers.remove(1);
        System.out.println("numbers.remove(1) => " + numbers);

        // Remove by object
        boolean removed = numbers.remove("Collections");
        System.out.println("numbers.remove(\"Collections\") => " + numbers);

        // Remove by predicate (Lambda)
        numbers.removeIf(s -> s.length() == 4);
        System.out.println("removeIf(s -> s.length() == 4) => " + numbers);

        //Delete all
        numbers.clear();
        System.out.println("numbers.clear() => " + numbers);
}
Output
original => [ArrayList, Java, Arrays, List, Collections]
numbers.remove(1) => [ArrayList, Arrays, List, Collections]
numbers.remove("Collections") => [ArrayList, Arrays, List]
removeIf(s -> s.length() == 4) => [ArrayList, Arrays]
numbers.clear() => []


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

The example below shows all 5 ways of iterating over ArrayList listed above.

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);
    }
}

Searching for Elements in ArrayList

We can search for elements in ArrayList using contains(object), indexOf(object) and lastIndexOf(object) methods.

import java.util.ArrayList;
public class ArrayList5 {
    public static void main(String[] args) {
        // Creating an array list and insert some elements
        ArrayList<String> numbers = new ArrayList<>();
        numbers.add("ArrayList");
        numbers.add("Java");
        numbers.add("Arrays");
        numbers.add("List");
        numbers.add("Collections");

        boolean result;

        result = numbers.contains("Collections");
        System.out.println("numbers.contains(\"Collections\") => " +  result);

        result = numbers.contains("C++"); // doesn't exist
        System.out.println("numbers.contains(\"C++\") => " +  result);

        int index;

        // Find the index of the first occurrence of an element
        index = numbers.indexOf("List");
        System.out.println("numbers.indexOf(\"List\") => " +  index);

        index = numbers.indexOf("Oracle"); // doesn't exist
        System.out.println("numbers.indexOf(\"Oracle\") => " +  index);

        // Find the index of the last occurrence of an element
        numbers.add("List"); // Add another "List" to the ArrayList
        index = numbers.lastIndexOf("List");
        System.out.println("numbers.indexOf(\"List\") => " +  index);
    }
}
Output
numbers.contains("Collections") => true
numbers.contains("C++") => false
numbers.indexOf("List") => 3
numbers.indexOf("Oracle") => -1
numbers.indexOf("List") => 5


ArrayList Properties

Multithreading

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 which returns a synchronized (thread-safe) list backed by the specified list.

Null and Duplicate Values

ArrayList allows null and duplicate values. The following are valid operations.

arrayList.add(null); // null is allowed
arrayList.add(1);
arrayList.add(null); // insert another null; duplicates are allowed too!

ArrayList Sorting

You can sort elements in an ArrayList using the Collections.sort() method or the ArrayList.sort() method.

Cheat Sheet

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.

#java #arraylist #list

You May Also Enjoy


If you like this post, please share using the buttons above. It will help CodeAhoy grow and add new content. Thank you!