Java ArrayList

In this post, you will learn everything about the Java ArrayList class and its methods with examples. The diagram below shows the hierarchy of the ArrayList class in the Java Collections Framework.

Java ArrayList Hierarchy

Key Points of Java ArrayList Class

1. Resizability

Unlike traditional arrays in Java, ArrayLists are dynamic and can grow or shrink as needed. This makes ArrayList a popular choice when working with an unknown number of objects.

2. Implements List Interface

ArrayList is part of the Java Collections Framework and implements the List interface, providing all the functionalities of a typical list data structure.

3. Supports Duplicate Elements

Unlike Set, ArrayList allows duplicate elements, meaning you can have any number of the same element in an ArrayList.

4. Maintains Insertion Order

ArrayList maintains the order of object insertion. The element added first will be the first element of the ArrayList and so on.

5. Random Access

ArrayList supports random access via index, just like an array. This makes getting elements from an ArrayList faster compared to other List implementations like LinkedList.

6. Manipulation Overhead

ArrayLists are slower when it comes to manipulation, such as the addition or removal of elements because it requires shifting of elements.

7. Not Synchronized

ArrayList is not synchronized, i.e., it is not thread-safe. If you need a thread-safe implementation, consider using Vector or Collections.synchronizedList().

8. Null Elements

ArrayList supports null elements. You can add null to an ArrayList.

9. Methods

ArrayList provides numerous methods for different operations like adding elements, removing elements, getting the size, checking if the list is empty, etc.

10. Iteration

ArrayList elements can be traversed using Iterator, ListIterator, loops, and enhanced for-loops.

11. Initial Capacity

While ArrayList can grow dynamically, it's beneficial to create it with an initial capacity if you have an estimate of the number of elements that will be added. This can help reduce the number of resizing operations.

12. Fail-Fast

The iterators returned by ArrayList's iterator and list iterator methods are fail-fast: if the ArrayList is structurally modified at any time after the iterator is created, except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException.

Create an ArrayList

You can create an ArrayList object using the following syntax:

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

It's generally a good practice to define the type of the collection by its interface rather than its implementation. This allows you to switch between different implementations easily if needed.

For example, using the List interface as type:

// Use List interface for declaration
List<String> list = new ArrayList<>();

Adding Elements to ArrayList

In Java, you can add elements to an ArrayList using the add() method. There are two forms of add() method in ArrayList:

  • boolean add(E element): This method appends the specified element to the end of the list. It always returns true.
  • void add(int index, E element): This method inserts the specified element at the specified position in this list. It shifts the element currently at that position (if any) and any subsequent elements to the right.

Here is how to use the add() method to add elements to an ArrayList:

// import the ArrayList class
import java.util.ArrayList;

public class Main {
  public static void main(String[] args) {
    // create an ArrayList
    ArrayList<String> fruits = new ArrayList<>();

    // add elements to the ArrayList
    fruits.add("Apple");
    fruits.add("Banana");
    fruits.add("Cherry");

    // print the ArrayList
    System.out.println(fruits);
  }
}

Output:

[Apple, Banana, Cherry]

To insert an element at a particular index in the ArrayList, you can use the add(int index, E element) method:

// import the ArrayList class
import java.util.ArrayList;

public class Main {
  public static void main(String[] args) {
    // create an ArrayList
    ArrayList<String> fruits = new ArrayList<>();

    // add elements to the ArrayList
    fruits.add("Apple");
    fruits.add("Banana");
    fruits.add("Cherry");

    // insert an element at index 1
    fruits.add(1, "Orange");

    // print the ArrayList
    System.out.println(fruits);
  }
}

Output:

[Apple, Orange, Banana, Cherry]

ArrayList Contains Null and Duplicate Values

Here is a simple example that demonstrates how a Java ArrayList can contain duplicates and null values:

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

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

        // Adding elements to the ArrayList
        list.add("Hello");
        list.add("World");
        list.add("Hello");  // This is a duplicate
        list.add(null);     // This is a null value

        // Displaying the elements in the ArrayList
        for(String str : list){
            System.out.println(str);
        }
    }
}

When you run this program, you will see that the ArrayList accepts both the duplicate "Hello" string and the null value. The output will be:

Hello
World
Hello
null

As you can see, the ArrayList has no issue accepting duplicate or null values. Each new element is simply added to the end of the list, in the order they were inserted.

Access Elements from the ArrayList

You can access elements of an ArrayList in Java using the get(int index) method. The get() method returns the element at the specified position in this list. The index parameter is zero-based, meaning the index of the first element is 0, the second element is 1, and so on.

Here's an example of how to use the get() method:

// import the ArrayList class
import java.util.ArrayList;

public class Main {
  public static void main(String[] args) {
    // create an ArrayList
    ArrayList<String> fruits = new ArrayList<>();

    // add elements to the ArrayList
    fruits.add("Apple");
    fruits.add("Banana");
    fruits.add("Cherry");

    // access the elements of the ArrayList
    String firstFruit = fruits.get(0);
    String secondFruit = fruits.get(1);
    String thirdFruit = fruits.get(2);

    // print the elements
    System.out.println("First fruit: " + firstFruit);
    System.out.println("Second fruit: " + secondFruit);
    System.out.println("Third fruit: " + thirdFruit);
  }
}

Output:

First fruit: Apple
Second fruit: Banana
Third fruit: Cherry

As you can see, get(0) returns the first element, get(1) returns the second element, and so on. Remember, if you try to access an index that does not exist (for example, if there are only 3 elements in the list and you try to access get(3) or get(4)), it will throw an IndexOutOfBoundsException.

Change or Update the ArrayList

In Java, you can modify or update an ArrayList using the set(int index, E element) method. The set() method replaces the element at the specified position in this list with the specified element.

Here's an example of how to use the set() method:

// Import the ArrayList class
import java.util.ArrayList;

public class Main {
  public static void main(String[] args) {
    // Create an ArrayList
    ArrayList<String> fruits = new ArrayList<>();

    // Add elements to the ArrayList
    fruits.add("Apple");
    fruits.add("Banana");
    fruits.add("Cherry");

    // Print the original ArrayList
    System.out.println("Original ArrayList: " + fruits);

    // Modify the elements of the ArrayList
    fruits.set(0, "Apricot");
    fruits.set(1, "Blueberry");
    fruits.set(2, "Cantaloupe");

    // Print the updated ArrayList
    System.out.println("Updated ArrayList: " + fruits);
  }
}

Output:

Original ArrayList: [Apple, Banana, Cherry]
Updated ArrayList: [Apricot, Blueberry, Cantaloupe]

Remove Elements from an ArrayList

The ArrayList class provides many methods to remove elements from the list based on the requirement. Let's discuss all the remove methods that ArrayList offers.

remove(int index)

This method removes the element at the specified position in this list.

List<String> programmingLanguages = new ArrayList<>();
programmingLanguages.add("C");
programmingLanguages.add("C++");
programmingLanguages.add("Java");
programmingLanguages.add("Kotlin");
// Remove the element at index `2`
programmingLanguages.remove(2);
System.out.println("After remove(2): " + programmingLanguages);

Output:

After remove(2): [C, C++, Kotlin]

remove(Object o)

This method removes the first occurrence of the specified element from this list, if it is present.

List<String> programmingLanguages = new ArrayList<>();
programmingLanguages.add("C");
programmingLanguages.add("C++");
programmingLanguages.add("Java");
programmingLanguages.add("Kotlin");
boolean isRemoved = programmingLanguages.remove("Kotlin");
System.out.println("After remove(\"Kotlin\"): " + programmingLanguages);

Output:

After remove("Kotlin"): [C, C++, Java]

removeAll(Collection<?> c)

The removeAll() method takes a collection of elements and removes all those elements from the list.

List<String> programmingLanguages = new ArrayList<>();
programmingLanguages.add("C");
programmingLanguages.add("C++");
programmingLanguages.add("Java");
programmingLanguages.add("Kotlin");

List<String> scriptingLanguages = new ArrayList<>();
scriptingLanguages.add("Java");
scriptingLanguages.add("Kotlin");

programmingLanguages.removeAll(scriptingLanguages);
System.out.println("After removeAll(scriptingLanguages): " + programmingLanguages);

Output:

After removeAll(scriptingLanguages): [C, C++]

removeIf(Predicate<? super E> filter)

Removes all of the elements of this collection that satisfy the given predicate.

List<String> programmingLanguages = new ArrayList<>();
programmingLanguages.add("C");
programmingLanguages.add("C++");
programmingLanguages.add("Java");
programmingLanguages.add("Kotlin");

// Remove all the elements that satisfy the given predicate
programmingLanguages.removeIf(s -> s.startsWith("C"));
System.out.println("After removeIf(): " + programmingLanguages);

Output:

After removeIf(): [Java, Kotlin]

clear()

Removes all of the elements from this list. The list will be empty after this call returns.

List<String> programmingLanguages = new ArrayList<>();
programmingLanguages.add("C");
programmingLanguages.add("C++");
programmingLanguages.add("Java");
programmingLanguages.add("Kotlin");

// Remove all elements from the ArrayList
programmingLanguages.clear();
System.out.println("After clear(): " + programmingLanguages);

Output:

After clear(): []

ArrayList Size

In Java, you can find the number of elements present in an ArrayList using the size() method. This method returns the number of elements in this list, i.e., the size of the ArrayList.

Here is an example:

import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        // Create an ArrayList
        ArrayList<String> fruits = new ArrayList<>();

        // Add elements to the ArrayList
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Cherry");

        // Print the size of the ArrayList
        System.out.println("Size of the ArrayList: " + fruits.size());
    }
}

Output:

Size of the ArrayList: 3

It's important to note that the size() method returns the number of elements in the ArrayList, not the capacity. The capacity is the size of the array used to store the elements in the list, and it is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically.

Iterate or Loop Over an ArrayList

ArrayList provides several ways to iterate over elements. Let's discuss all of them with an example.

Using Traditional for loop:

ArrayList<String> list = new ArrayList<>();
list.add("Java");
list.add("Python");
list.add("C++");

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

Using Enhanced for loop:

ArrayList<String> list = new ArrayList<>();
list.add("Java");
list.add("Python");
list.add("C++");

for(String item : list) {
  System.out.println(item);
}

Using Iterator:

ArrayList<String> list = new ArrayList<>();
list.add("Java");
list.add("Python");
list.add("C++");

Iterator<String> it = list.iterator();
while(it.hasNext()) {
  System.out.println(it.next());
}

Using ListIterator (which can iterate in both directions):

ArrayList<String> list = new ArrayList<>();
list.add("Java");
list.add("Python");
list.add("C++");

ListIterator<String> lit = list.listIterator(list.size());
while(lit.hasPrevious()) {
  System.out.println(lit.previous());
}

Using forEach() method with Java 8 Lambda expression:

ArrayList<String> list = new ArrayList<>();
list.add("Java");
list.add("Python");
list.add("C++");

list.forEach(item -> System.out.println(item));

Each of these methods has its use cases and can be used depending on the requirements of the specific situation.

Search Elements in an ArrayList

Searching for elements in an ArrayList can be achieved using different methods in Java. Here are a few common ways:

Using the contains() method

This is the simplest way to check if an ArrayList contains a specific element. It returns true if the list contains the specified element, and false otherwise.

ArrayList<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");

if (fruits.contains("Banana")) {
    System.out.println("Banana is in the list");
} else {
    System.out.println("Banana is not in the list");
}

Using the indexOf() method

This method returns the index of the first occurrence of the specified element in the list, or -1 if the list does not contain the element.

int index = fruits.indexOf("Banana");
if (index != -1) {
    System.out.println("Banana is in the list at index: " + index);
} else {
    System.out.println("Banana is not in the list");
}

Using the stream() method and the anyMatch() function (Java 8 and later)

This approach is useful when you need to check for elements that satisfy a certain condition, not just for exact matches.

boolean hasBanana = fruits.stream().anyMatch(fruit -> fruit.equals("Banana"));
System.out.println(hasBanana ? "The list contains Banana" : "The list does not contain Banana");

Sort an ArrayList

Let's go with an example that sorts an ArrayList of Strings and an ArrayList of integers in ascending and descending order.

Here is an example of sorting an ArrayList of Strings:

import java.util.ArrayList;
import java.util.Collections;

public class Main {
    public static void main(String[] args) {
        ArrayList<String> countries = new ArrayList<>();
        countries.add("USA");
        countries.add("China");
        countries.add("India");
        countries.add("Australia");
        countries.add("Germany");

        System.out.println("Original ArrayList: " + countries);

        Collections.sort(countries);
        System.out.println("Sorted in Ascending order: " + countries);

        Collections.sort(countries, Collections.reverseOrder());
        System.out.println("Sorted in Descending order: " + countries);
    }
}

Output:

Original ArrayList: [USA, China, India, Australia, Germany]
Sorted in Ascending order: [Australia, China, Germany, India, USA]
Sorted in Descending order: [USA, India, Germany, China, Australia]

And here is an example of sorting an ArrayList of Integers:

import java.util.ArrayList;
import java.util.Collections;

public class Main {
    public static void main(String[] args) {
        ArrayList<Integer> numbers = new ArrayList<>();
        numbers.add(10);
        numbers.add(5);
        numbers.add(50);
        numbers.add(30);
        numbers.add(15);

        System.out.println("Original ArrayList: " + numbers);

        Collections.sort(numbers);
        System.out.println("Sorted in Ascending order: " + numbers);

        Collections.sort(numbers, Collections.reverseOrder());
        System.out.println("Sorted in Descending order: " + numbers);
    }
}

Output:

Original ArrayList: [10, 5, 50, 30, 15]
Sorted in Ascending order: [5, 10, 15, 30, 50]
Sorted in Descending

 order: [50, 30, 15, 10, 5]

Conclusion

In this article, you learned what an ArrayList is, how to create an ArrayList, how to add, modify, and remove elements from an ArrayList, how to iterate over an ArrayList, how to sort an ArrayList, and more. Thank you for reading. See you in the next post!

Comments