Thread safe Java List implementations tutorial


In this tutorial, we are going to discuss the most important things about the Java ArrayList class. Here we are not going to discuss everything about ArrayList but the most important things about Java ArrayList, which will help java developers to face technical job interviews and refresh their memory.


public class TestArrayList {

    private static List arrayList;

    public static void testArrayList() {
        arrayList = new ArrayList<>();

        arrayList.add(1);       //adding elements
        arrayList.add(2);
        arrayList.add(1);
        arrayList.add(1, 4);    //adding element to the index 1

        for (Integer var : arrayList) { //for loop
            System.out.println(var);
        }

        arrayList.remove(1);    //remove element in index 1

        arrayList.forEach(var -> System.out.println(var));  //java 8 foreach loop

        System.out.println(arrayList.size());   //get size of the arrayList
    }
}

Properties of Java ArrayList class

  • Java ArrayList is a resizable array implementation of the List interface.
  • Java ArrayList is an ordered collection of objects.
  • Java ArrayList can have duplicate items.
  • Java ArrayList allows multiple null elements.
  • Java ArrayList is unsynchronized (Not thread-safe). Developers need to be very careful if using for parallel processing.
  • Objects can access by their index (position in the list).
  •     arrayList.get(1);

  • Objects can insert into the Java ArrayList by the desired index.
  •     arrayList.add(1);       //adding elements from the end
        arrayList.add(1, 4);    //adding element to the index 1

  • Objects can remove from the Java ArrayList by the desired index.
  •     arrayList.remove(2);    //remove element by index
        arrayList.remove("Object");     //remove an object

  • The Java ArrayList provides facility to insert and remove multiple elements at an arbitrary point in the list.
  • "The size, isEmpty, get, set, iterator, and listIterator operations run in constant time. The add operation runs in amortized constant time, that is, adding n elements requires O(n) time. All of the other operations run in linear time (roughly speaking). The constant factor is low compared to that for the LinkedList implementation."

  • Each ArrayList instance has a specific size(capacity). When the elements are adding to it, its size(capacity) grows automatically.

Oracle documentation for Java ArrayList


How to synchronize a Java ArrayList instance ?

By default Java, ArrayList implementation is not synchronized. If multiple threads going to access Java ArrayList instance, developers have to make it synchronized. We can achieve this by externally synchronizing the Java ArrayList instance with the Collections.synchronizedList method.

    List list = Collections.synchronizedList(new ArrayList(...));


<< Java Collections Framework      Sorting a Java ArrayList >>