Introduction to the Java ArrayList

In this post, we will cover features of Java ArrayList class. We will discuss its features and well-known use cases.

Java ArrayList

The ArrayList class is the part of Java Collection Framework. This class implements the List interface provided by the Collection framework. This is a high level hierarchy for the Array list. This is one of the most widely used in Java because it provides flexibility. Java ArrayList is the preferred data structure for everyone who needs dynamic array.

Java ArrayList

Here are features or key points about the ArrayList in Java:

  1. The Java ArrayList grow and sink dynamically when we add/remove elements from it.
  2. ArrayList uses the array as an internal data structure to store element.
  3. This provides flexibility to use elements using the indexes.
  4. ArrayList allows to store duplicate values including “null” values.
  5. It is an ordered collection, i.e. it maintains the insertion order.
  6. Java ArrayList supports Generics.
  7. It only allows objects in the ArrayList. For primitive values like int, long etc. use the wrapper classes.
  8. Java ArrayList Iterator and ListIterator implementation is fail-fast.
  9. ArrayList is not thread safe. We need to apply synchronization if multiple threads will change ArrayList at the same time.

Here are known parameters for the Java ArrayList complexity.

  • Add operation has O(1) complexity.
  • Remove has O(1) complexity.
  • Contains operation have O(n) complexity.

Internally ArrayList is a resizable-array implementation of the List interface. Here is a sample code with Java ArrayList.

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

public class ArrayListExample {

 public static void main(String[] args) {

  List < String > list = new ArrayList < String > ();

  //Add operation
  list.add("California");
  list.add("Alabama");
  list.add("Colorado");
  list.add("Delaware");
  list.add(4, "Texas"); //add based on index

  list.contains("Virginia"); //false

  list.remove("Colorado");
  list.remove(1); //remove by index
 }
}

Let’s inspect the ArrayList

1. Arrays vs ArrayList

Once you work on the ArrayList in Java, you might start thinking about ArrayList vs Array.In this section we will see some of the limitation of Array.

  1. Array has a fixed width and you need to specify the size upfront before you use it and its size will remain same even if you remove all elements from the Array. On the other hand ArrayList is dynamic in nature and it will grow or shrink automatically as we add/ remove element from it.
  2. Array is just data storage and you need to write the code to work on the Array (e.g. Add, remove or search etc.) While the ArrayList provides a set of methods which make it easy to work with it.

Keep in mind that ArrayList is not better than Array but it’s a better choice if you don’t know the size upfront and need a dynamic Array. If you know the size, Array is a better choice and provides efficiency and speed. Choose your data structure carefully!!

2. How to Create ArrayList

On a high level, we have the following way to create a new ArrayList in Java.

  • Use a default constructor.
  • Pass initial capacity in the constructor.
  • Pass Java Collection as a constructor parameter.

2.1 Default Constructor

This is one of the most common ways to create ArrayList in Java. We are creating an empty ArrayList of type String.You can remove the type parameter (<String>) from the declaration but that is not recommended as you will lose the data integrity check from the compiler.

List<String> list= new ArrayList<String>();

Remove the type parameter and check if you can add different types in your list (e.g. String, Integer or any custom class).

2.2  Constructor with Initial Capacity

This option allows us to construct an empty list with the specified initial capacity. This is helpful to avoid frequent resizing during the add operation. Keep in mind when ArrayList reaches a certain threshold (number of elements in ArrayList reach a certain percentage of the capacity), it will internally perform the following additional operation.

  1. Create a new Array (remember ArrayList use Array internally) which is double the capacity of original Array.
  2. Copy all the elements from the old Array to the new Array.
  3. This is time-consuming especially if your ArrayList is bigger (imagine, your ArrayList contains 10000 elements and now system need to increase the size)
List<String> list= new ArrayList<String>(10);

2.3  Constructor with Collection

This method helps to construct a list containing the elements of the specified collection.

List<String> intialList = Arrays.asList("California","Alabama");
List<String> list= new ArrayList<String>(intialList)

While creating ArrayList, we should keep in mind following extra points.

  • ArrayList is generic, and it’s always recommended to pass element type to let compiler make sure data integrity.
  • ArrayList implements List interface, and it’s a good practice to use generic interface for better decoupling.

3. How to Add Elements to an ArrayList

We can add elements by calling add() method. The ArrayList add() method is overloaded and provides few variations which we can use based on our requirement.

  1. Simply calling list.add("value") will add the element at the end of the list.
  2. The void add(int index, E element) will add the element at the specified index.
List<String> list= new ArrayList<String>();
list.add("California");
list.add(4,"Texas");

If you want to add multiple elements (e.g. another ArrayList of Set), We can use the addAll() method to do that.

List<String> intialList = Arrays.asList("California1","Alabama1");
List<String> list= new ArrayList<String>();
list.addAll(intialList);

Let’s see both variations with complete examples for better understanding.

3.1 Creating an ArrayList and adding elements

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

public class ArrayListExample {

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

  // Adding new elements to the ArrayList
  states.add("California");
  states.add("Alabama");
  states.add("Florida");
  states.add("Hawaii");
  states.add("New York");

  System.out.println(states);

  // Adding an element at a particular index in an ArrayList
  states.add(3, "Texas");

  System.out.println(states);
 }
}
#Output
[California, Alabama, Florida, Hawaii, New York]
[California, Alabama, Florida, Texas, Hawaii, New York]

Keep in mind that index start with 0, so states.add(3, "Texas") will add at the 4th position and not 3rd

3.2 Creating an ArrayList from Collection

There are two options to create an ArrayList from another collection.

  1. Use the ArrayList​(Collection<? extends E> c) constructor to pass the collection as a parameter.
  2.  Use addAll​(Collection<? extends E> c) method to append all the elements in the specified collection to the end of this list.
public class ArrayListExample {

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

  //Adding new elements to the ArrayList
  states.add("California");
  states.add("Alabama");
  states.add("Florida");
  states.add("Hawaii");
  states.add("New York");

  //Creating an ArrayList from another collection
  List <String> newStateList = new ArrayList <String> (states);
  System.out.println(newStateList);

  List <String> additionalStates = new ArrayList<String> ();
  additionalStates.add("Washington");
  additionalStates.add("Wisconsin");
  additionalStates.add("Missouri");

  //Adding an entire collection to an ArrayList
  newStateList.addAll(additionalStates);

  System.out.println(newStateList);

 }
}
#Output
[California, Alabama, Florida, Hawaii, New York]
[California, Alabama, Florida, Hawaii, New York, Washington, Wisconsin, Missouri]

4. How to Remove Elements from ArrayList

There are two variations of the remove operation in ArrayList.

  • Use remove() method to remove an element by value or using an index. remove() by Object will remove the first occurrence of the specified element from this list.
  • Use removeAll() to remove from this list all of its elements that are contained in the specified collection.
public class ArrayListExample {

    public static void main(String[] args) {

        List < String > list = new ArrayList < String > ();
        list.add("California");
        list.add("Alabama");
        list.add("Colorado");
        list.add("Delaware");

        System.out.println(list);

        //remove element By value.This will use equal internally
        list.remove("Colorado");
        list.remove(1); //remove by index

        //display output after remove operation
        System.out.println(list);

        //removing element by passing collection
        List < String > removeCollection = Arrays.asList("California", "Alabama");
        list.removeAll(removeCollection);

        //display output after remove operation
        System.out.println(list);
    }
}
#output
[California, Alabama, Colorado, Delaware]
[California, Delaware]
[Delaware]

5. Change an Element from ArrayList

At some point, you may want to change element in the ArrayList, you can use the set(int index, E element) method to do that.The first element is the index where we want to change element and second argument is the element which we need to change.

public class ArrayListExample {

    public static void main(String[] args) {

        List < String > list = new ArrayList < String > ();
        list.add("California");
        list.add("Alabama");
        list.add("Colorado");
        list.add("Delaware");

        System.out.println(list);

        //change element at position 3
        list.set(2, "Texas");

        //display output after remove operation
        System.out.println(list);
    }
}
#output
[California, Alabama, Colorado, Delaware]
[California, Alabama, Texas, Delaware]

6. How to Iterate ArrayList

We have two different ways to iterate elements of the Java ArrayList.

  • Iterator – Provide option to iterate a list in one direction.
  • Listiterator – An iterator for lists that allows the programmer to traverse the list in either direction.
List < Integer > integerList = Arrays.asList(1, 2, 3, 6, 7, 4, 9, 11, 34, 12, 22);
 ListIterator < Integer > listIterator = integerList.listIterator();
 while (listIterator.hasNext()) {
  System.out.println("Next element is " + listIterator.next());
 }
 while (listIterator.hasPrevious()) {
  System.out.println("Previous element is " + listIterator.previous());
 }

Java 8 brought several fundamental changes to the API. Use forEach() method directly in the list to perform the action for each element of the Iterable until it has processed all elements, or the action throws an exception.

7. Search

ArrayList provides several options to search elements through the list.

  • Use indexOf() and lastIndexOf() methods to get index element for the method.
  • contains(Object) – Returns true if this list contains the specified element.
List < String > stringList = Arrays.asList("California", "Alabama", "Colorado", "Delaware", "Virginia");
assertEquals(1, stringList.indexOf("Alabama"));

If your code requires the frequent check for specific elements, better to use a HashSet than an ArrayList. Java doc for HashSet says: “This class offers constant time performance for the basic operations (add, remove, contains and size)”

8. Access Elements from ArrayList

The ArrayList provides following methods to access its values or state:

  • Use the size() method to find the size of ArrayList.
  • The Get() method provides the element at a particular index in an ArrayList.
  • Use the set() method to change or set element at a particular index.
  • The isEmpty() method to check if ArrayList is empty.
import java.util.ArrayList;
import java.util.List;

public class ArrayListExample {

    public static void main(String[] args) {
        // Creating an ArrayList of String
        List states = new ArrayList<>();
        System.out.println("Is State list is empty: "+states.isEmpty());
        
        // Adding new elements to the ArrayList
        states.add("California");
        states.add("Alabama");
        states.add("Florida");
        states.add("Hawaii");
        states.add("New York");

        
        System.out.println("Number of states in our ArrayList is: "+states.size());
        System.out.println("First State in our list is: "+states.get(0));
        
        //let's modify out list
        states.set(0,"Alaska ");
        System.out.println("New first State in our list is: "+states.get(0));
    }
}
#Output:
Is State list is empty: true
Number of states in our ArrayList is: 5
First State in our list is: California
New first State in our list is: Alaska 

Summary

In this post, we discussed the ArrayList in Java. We learned how to create a new ArrayList in Java and how to do different operations on the ArrayList.The source code for this article is available on our GitHub repository.