ArrayList - Examples and practice problems

ArrayList in Java is used to store dynamically sized collection of elements. Contrary to Arrays that are fixed in size, an ArrayList grows its size automatically when new elements are added to it.

ArrayList is part of Java’s collection framework and implements Java’s List interface.Java ArrayList in Collection Hierarchy

Following are few key points to note about ArrayList in Java -

  • An ArrayList is a re-sizable array, also called a dynamic array. It grows its size to accommodate new elements and shrinks the size when the elements are removed.

  • ArrayList internally uses an array to store the elements. Just like arrays, It allows you to retrieve the elements by their index.

  • Java ArrayList allows duplicate and null values.

  • Java ArrayList is an ordered collection. It maintains the insertion order of the elements.

  • You cannot create an ArrayList of primitive types like int, char etc. You need to use boxed types like Integer, Character, Boolean etc.

  • Java ArrayList is not synchronized. If multiple threads try to modify an ArrayList at the same time, then the final outcome will be non-deterministic. You must explicitly synchronize access to an ArrayList if multiple threads are gonna modify it.

Creating an ArrayList and adding new elements to it

This example shows:

  • How to create an ArrayList using the ArrayList() constructor.

  • Add new elements to an ArrayList using the add() method.

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

public class CreateArrayListExample {

    public static void main(String[] args) {
        // Creating an ArrayList of String
        List<String> animals = new ArrayList<>();

        // Adding new elements to the ArrayList
        animals.add("Lion");
        animals.add("Tiger");
        animals.add("Cat");
        animals.add("Dog");

        System.out.println(animals);

        // Adding an element at a particular index in an ArrayList
        animals.add(2, "Elephant");

        System.out.println(animals);

    }
}

Creating an ArrayList from another collection

This example shows:

  • How to create an ArrayList from another collection using the ArrayList(Collection c)constructor.

  • How to add all the elements from an existing collection to the new ArrayList using the addAll()method.

Accessing elements from an ArrayList

This example shows:

  • How to check if an ArrayList is empty using the isEmpty() method.

  • How to find the size of an ArrayList using the size() method.

  • How to access the element at a particular index in an ArrayList using the get() method.

  • How to modify the element at a particular index in an ArrayList using the set() method.

Removing elements from an ArrayList

This example shows:

  1. How to remove the element at a given index in an ArrayList | remove(int index)

  2. How to remove an element from an ArrayList | remove(Object o)

  3. How to remove all the elements from an ArrayList that exist in a given collection | removeAll()

  4. How to remove all the elements matching a given predicate | removeIf()

  5. How to clear an ArrayList | clear()

Iterating over an ArrayList

The following example shows how to iterate over an ArrayList using

  1. Java 8 forEach and lambda expression.

  2. iterator() and Java 8 forEachRemaining() method.

  3. Simple for-each loop.

  4. for loop with index.

The iterator() and listIterator() methods are useful when you need to modify the ArrayList while traversing.

Consider the following example, where we remove elements from the ArrayList using iterator.remove() method while traversing through it -

Searching for elements in an ArrayList

The example below shows how to:

  • Check if an ArrayList contains a given element | contains()

  • Find the index of the first occurrence of an element in an ArrayList | indexOf()

  • Find the index of the last occurrence of an element in an ArrayList | lastIndexOf()

ArrayList of user defined objects

Since ArrayList supports generics, you can create an ArrayList of any type. It can be of simple types like Integer, String, Double or complex types like an ArrayList of ArrayLists, or an ArrayList of HashMaps or an ArrayList of any user defined objects.

In the following example, you’ll learn how to create an ArrayList of user defined objects.

Sorting an ArrayList

Sorting an ArrayList is a very common task that you will encounter in your programs. In this section, I’ll show you how to -

1. Sort an ArrayList using Collections.sort() method

2. Sort an ArrayList using ArrayList.sort() method

3. Sort an ArrayList of Objects using custom Comparator

Synchronizing Access to an ArrayList

The ArrayList class is not synchronized. If multiple threads try to modify an ArrayList at the same time then the final result becomes not-deterministic because one thread might override the changes done by another thread.

Example Demonstrating ArrayList’s unpredictable behavior in multi-threaded environments

The following example shows what happens when multiple threads try to modify an ArrayList at the same time.

The final output of the above program should be equal to [101, 102, 103] because we’re incrementing the values in the ArrayList 100 times. But if you run the program, it will produce different output every time it is run -

Try running the above program multiple times and see how it produces different outputs. To learn more about such issues in multi-threaded programs, check out my article on Java Concurrency Issues and Thread Synchronization.

Example demonstrating how to synchronize concurrent modifications to an ArrayList

All right! Now let’s see how we can synchronize access to the ArrayList in multi-threaded environments.

The following example shows the synchronized version of the previous example. Unlike the previous program, the output of this program is deterministic and will always be the same.

The above example uses Collections.synchronizedList() method to get a synchronized view of the ArrayList.

Moreover, the modifications to the ArrayList inside the incrementArrayList() method is wrapped inside a synchronized block. This ensures that no two threads can increment ArrayList elements at the same time.

You can also use a CopyOnWriteArrayList if you need thread safety. It is a thread-safe version of the ArrayList class. It implements all the mutating operations by making a fresh copy of the ArrayList.

More Examples :

Example a: Add an element to specified index of Java ArrayList Example

Example b: Get Size of Java ArrayList and loop through elements Example

Example c: Search an element of Java ArrayList Example

Example d: Get Sub List of Java ArrayList Example

Example e: Remove an element from specified index of Java ArrayList

Example f: Sort elements of Java ArrayList

Example 1:

Example 2:

Java ArrayList Iterator

Iterator is an interface in Java Collections framework. ArrayList provides fail-fast iterator implementation. When you want to perform some operation on all the list elements, you should use Iterator. If any structural modification is made to the list while iterating, it’s next() operation will throw ConcurrentModificationException. Below is a simple example of ArrayList iterator.

Example 3:

Example 4: Copy elements from one arraylist to another:

Example 5: Find maximum element of Java ArrayList.

Example 6: Find Minimum element of Java ArrayList

Example 7: Swap elements of Java ArrayList

Quiz :

Problems:

1. Write a Java program to create a new array list, add some colors (string) and print out the collection. Go to the editor Click me to see the solution

2. Write a Java program to iterate through all elements in a array list. Go to the editor Click me to see the solution

3. Write a Java program to insert an element into the array list at the first position. Go to the editor Click me to see the solution

4. Write a Java program to retrieve an element (at a specified index) from a given array list. Go to the editor Click me to see the solution

5. Write a Java program to update specific array element by given element. Go to the editor Click me to see the solution

6. Write a Java program to remove the third element from a array list. Go to the editor Click me to see the solution

7. Write a Java program to search an element in a array list. Go to the editor Click me to see the solution

8. Write a Java program to sort a given array list. Go to the editor Click me to see the solution

9. Write a Java program to copy one array list into another. Go to the editor Click me to see the solution

10. Write a Java program to shuffle elements in a array list. Go to the editor Click me to see the solution

11. Write a Java program to reverse elements in a array list. Go to the editor Click me to see the solution

12. Write a Java program to extract a portion of a array list. Go to the editor Click me to see the solution

13. Write a Java program to compare two array lists. Go to the editor Click me to see the solution

14. Write a Java program of swap two elements in an array list. Go to the editor Click me to see the solution

15. Write a Java program to join two array lists. Go to the editor Click me to see the solution

16. Write a Java program to clone an array list to another array list. Go to the editor Click me to see the solution

17. Write a Java program to empty an array list. Go to the editor Click me to see the solution

18. Write a Java program to test an array list is empty or not. Go to the editor Click me to see the solution

19. Write a Java program to trim the capacity of an array list the current list size. Go to the editor Click me to see the solution

20. Write a Java program to increase the size of an array list. Go to the editor Click me to see the solution

21. Write a Java program to replace the second element of a ArrayList with the specified element. Go to the editor Click me to see the solution

22. Write a Java program to print all the elements of a ArrayList using the position of the elements. Go to the editor Click me to see the solution

Coding Challenges :

Last updated

Was this helpful?