ArrayList in Java | Methods, Example

ArrayList in Java is a dynamic array that allows us to store multiple objects of any class or data type. It is similar to an array, but there is no fixed size limit. It was added to the Java programming in JDK 1.2 as part of the Java Collections Framework.

ArrayList class is present in the java.util package and is commonly used for storing and manipulating collections of objects in an arbitrary order.

An ArrayList is a resizable array that can grow or shrink in the memory whenever needed. It is dynamically created with an initial capacity. It means that if the initial capacity of the array is exceeded, a new array with larger capacity is created automatically and all the elements from the current array are copied to the new array.

Elements in ArrayList are placed according to the zero-based index. That is the first element will be placed at 0 index and the last element at index (n-1) where n is the size of ArrayList.

Java ArrayList uses a dynamic array internally for storing the group of elements, objects, or data. The capacity of ArrayList does not shrink automatically. When elements are removed from the list, the size of array list can be shrunk automatically but not capacity.

Hierarchy Diagram of ArrayList Class in Java

The hierarchy diagram of ArrayList class in Java has shown in the below figure.

Hierarchy diagram of ArrayList in Java

As shown in the above hierarchy diagram, ArrayList class implements the List interface and extends AbstractList (Abstract class) which implements List interface.

ArrayList class also implements 3 marker interfaces in Java. They are Random Access, Cloneable, and Serializable.

A marker interface is an interface that does not have any methods or any member variables. It is also called an empty interface because of no field or methods.

Random Access Interface

1. RandomAccess Interface is a marker interface that does not define any method or member. It is introduced in Java 1.4 version for optimizing the list performance.

2. RandomAccess interface is present in java.util package.

3. ArrayList class implements a random access interface so that we can access any random element at the same speed. For example, suppose there is a group of one crore objects in the array list. Assume that the first element is x, 10th element is y, and 1st crore element is z.

Now assume that first element x can be accessed within only 1 sec.  Due to the implementation of random access interface, the 10th element and 1st crore element can also be accessed within 1 sec.

Thus, Any random element we can access with the same or constant speed. Therefore, if our frequent operation is retrieval operation then ArrayList is the best choice.

Serializable Interface

1. A serializable interface is a marker interface that is used to send the group of objects over the network. It is present in the package.

2. It helps in sending the data from one class to another class. Usually, we use collections to hold and transfer objects from one place to another place.

To provide support for this requirement, every collections class already implements Serializable and Cloneable.

Cloneable Interface

1. A cloneable interface is present in java.lang package.

2. It is used to create exactly duplicate objects. When the data or group of objects came from the network, the receiver will create duplicate objects.

The process of creating exactly duplicate objects is known as cloning. It is a very common requirement for collection classes.

Features of ArrayList in Java

There are several features of ArrayList class in Java. They are as follows:

1. Resizable-array: ArrayList is a resizable array or growable array that means the size of ArrayList can increase or decrease in size at runtime. Once ArrayList is created, we can add any number of elements.

2. Index-based structure: It uses an index-based structure in java.

3. Duplicate elements: Duplicate elements are allowed in the array list.

4. Null elements: Any number of null elements can be added to ArrayList.

5. Insertion order: It maintains the insertion order in Java. That is insertion order is preserved.

6. Heterogeneous objects: Heterogeneous objects are allowed everywhere except TreeSet and TreeMap. Heterogeneous means different elements.

7. Synchronized: ArrayList is not synchronized. That means multiple threads can use the same ArrayList objects simultaneously.

8. Random Access: ArrayList implements random access because it uses an index-based structure. Therefore, we can get, set, insert, and remove elements of the array list from any arbitrary position.

9. Performance: In ArrayList, manipulation is slow because if any element is removed from ArrayList, a lot of shifting takes place.

For example, if an array list has 500 elements and we remove 50th elements then the 51st element will try to acquire that 50th position, and likewise all elements. Thus, it consumes a lot of time-shifting.

Java ArrayList Constructor

Java ArrayList class provides three constructors for creating an object of ArrayList. They are as:

  • ArrayList()
  • ArrayList(int initialCapacity)
  • ArrayList(Collection c)

Creating an object of ArrayList class in Java is very simple. First, we will declare an array list variable and call the array list constructor to instantiate an object of ArrayList class and then assign it to the variable.

Syntax to Create ArrayList

We can create an object of ArrayList class in java by using any one of three constructors. Let’s see one by one.

1. The syntax for creating an instance of ArrayList class is as:

ArrayList al = new ArrayList();

It creates an empty ArrayList with a default initial capacity of 10. In this array list, we can store only 10 elements as shown in the below diagram.

ArrayList Constructor in Java

Suppose we insert the 11th element at 10th position into an array list, what will happen internally?

Once ArrayList is reached its maximum capacity, the ArrayList class automatically creates a new array with a larger capacity.

New capacity = (current capacity*3/2) + 1 = 10*3/2 + 1 = 16

After creating a new array list with a larger capacity, all the existing elements are copied into the new array list and then adds the new element into it. ArrayList class reassigns the reference to the new array objects as shown in the above figure.

The old default array list with the collection of objects is automatically gone into the garbage collection. Similarly, If we try to insert 17th element, new capacity= 16*3/2 + 1 = 25.

Another Ways to Create ArrayList

2. We can also initialize the capacity at the time of creating ArrayList object.  The syntax for creating an instance of ArrayList class with initial capacity is as:

ArrayList al = new ArrayList(int initialCapacity);

It creates an empty ArrayList with initial capacity. If you know the initial capacity, you can directly use this method. Thus, we can improve the performance of the system by default.

For example, suppose our requirement is to add 500 elements in the array list, we will create ArrayList object like this:

ArrayList list2 = new ArrayList(500);

3. We can also create an object of ArrayList class by initializing a collection of elements into it. The syntax is as follow:

ArrayList al = new ArrayList(Collection c);

It creates an ArrayList object by initializing elements of collection c.

For example:

ArrayList list3 = new ArrayList(list1); // list1 is elements of collection.

Creating Generic ArrayList Object in Java

Java 1.5 version or later also provides us to specify the type of elements in the ArrayList object. For example, we can create a generic String ArrayList object like this:

// This statement will store elements of only string type.
// An advantage of specifying a type is when we try to add another type of element, it will give compile-time error.
   ArrayList<String> al = new ArrayList<String>();  

// We can also create a generic ArrayList object in separate lines like this:
   ArrayList<String> arlist;    
         arlist = new ArrayList();

Note: We cannot use primitive data types as a type. For example, ArrayList<int> is illegal.

How to Initialize ArrayList in Java

There are three methods to initialize the array list in Java. They are as follows:

1. Using Arrays.asList: The syntax to initialize an ArrayList using asList() method is as follows:

ArrayList<Type> list = new ArrayList<Type>(Arrays.asList(Object o1, Object o2, .. so on));

For example:
  ArrayList<String> ar = new ArrayList<String>(Arrays.asList("A", "B", "C"))

2: Using normal way: This is a popular way to initialize ArrayList in java program. The syntax to initialize array list is as:

ArrayList<Type> obj = new ArrayList<Type>();   
  obj.add("Obj o1");
  obj.add("Obj o2");
  and so on.

3. Using Anonymous Inner class: The syntax for initialization of ArrayList in java using anonymous inner class is as:

ArrayList<Type> arl = new Arraylist<Type>() {{   
   add(Object o1);
   add(Object o2);
   add(Object o3);
   . . . . . . . . 
   . . . . . . . 

ArrayList Methods in Java

ArrayList class provides a variety of useful methods for adding, removing, accessing, and updating elements. These methods are easy to use and type-safe.

However, it can have a slow performance when dealing with a large data. So, let’s understand all the methods provided by ArrayList with examples.

1. boolean add(Object o): This method is used to add an element at the end of array list. For example,  if you want to add an element at the end of the list, you simply call the add() method like this:

list.add("Shubh"); // This will add "Shubh" at the end of the list.

2. boolean addAll(Collection c): This method is used to add a group of elements in a particular collection at the end of the list. For example, suppose we have a group of elements in the list2 and want to add at the end of the list1, we will call this method like this:


3. boolean addAll(int index, Collection c): This method is used to add a group of elements at a specified position in a list. For example:

list1.addAll(2, list2): // Adding all elements of list2 at position index 2 in list1

4. void add(int index, Object o): It is used to add an element at a particular position index in the list. For example:

list.add(3, "a"); // Adding element 'a' at position index 3 in list.

5. void addAll(int index, Object o): It is used to add a specific element at a particular position in the list. For example, suppose we want to a specific element “Shubh” at a position 2 in the list, we will call add(int index, Object o) method like this:

list.add(2,"Shubh"); // This will add "Shubh" at the second position.

Let’s take an example program based on all the variety of add() methods provided by Java array list.

Example 1:

package ArrayListTest; 
import java.util.ArrayList; 
public class AddExample { 
public static void main(String[] args) 
// Create an object of the non-generic ArrayList. 
   ArrayList al = new ArrayList(); // list 1 with default capacity 10. 

// Create an object of another non-generic ArrayList. 
   ArrayList al1 = new ArrayList(); // list 2.

// Call addAll(Collection c) method using reference variable al to add all elements at the end of the list1.

// Call addAll(int index, Collection c) method using reference al1 to add all elements at specified position 2. 
    al1.addAll(2, al); 
       [A, B, 20, A, null] 
       [A, B, 20, A, null, a, b, c] 
       [a, b, A, B, 20, A, null, a, b, c, c]

In this example, we have created two ArrayList objects called “al” and “al1” that will hold objects of any data type. Then, we use the add() and addAll() methods to add elements of the ArrayList.

In this program, we have used duplicate elements, heterogeneous elements (i.e. String and Integer), and a null element. You will also notice that when a specified element is added at a particular position, the right side element is shifted one position right.

After shifting, the object reference variable will reassign a new array list as shown in the above picture. Due to shifting, ArrayList is also time-consuming.

In the output, we are getting square bracket notation for this ArrayList. This is because when we try to print an object reference variable, internally it calls toString() method like this:

System.out.println(al); ------> System.out.println(al.toString());

5. boolean remove(Object o): It removes the first occurrence of the specified element from this list if it is present.

6. void remove(int index): This method removes the element from a particular position in the list. Look at the examples below.

list.remove(2); // It will remove element from position 2.

7. void clear(): The clear() method is used to remove all elements from an array list.

8. void set(int index, Object o): The set() method replaces element at a particular position in the list with the specified element. For example, suppose we want to replace an element “A” at a position 2 with an element “a” in the list, we will have to call this method as:

list.set(2, "a");

Let’s take an example program in which we will remove an element using remove() method from the array list.

Example 2:

package ArrayListTest; 
import java.util.ArrayList; 
public class RemoveEx 
public static void main(String[] args) 
// Create a generic Arraylist object of String type. 
// This means the compiler will show an error if we try to put any other element than String. 
   ArrayList<String> al = new ArrayList<String>(); // Default capacity is 10. 

// Adding elements of String type. 

// Call remove() method to remove element D.
// This statement removes the first occurrence of the specified element D at position 3, not from the position 5. 

// Call set() method to replace an element D with a null element at position 3. 
    al.set(3, null); 
      [A, B, C, D, null, D] 
      [A, B, C, null, D] 
      [A, B, C, D] 
      [A, B, C, null]

In this example program, you will observe that when an element is removed or deleted from an array, the deleted element becomes null but the empty slot occupied by the deleted element stays in the array.

Any subsequent elements at the right side in the array are automatically shifted towards one position left to fill empty slot that was occupied by deleted element and object reference variable ‘al’ will be reassigned to the new array list like as shown in the above diagram.

9. Object get(int index): It returns the element at the specified position in this list.

10. int size(): It returns the number of elements of the list. Size means the number of elements present in the array list. Capacity means the capability to store elements.

11. boolean contains(Object o): It returns true if a specified element is present in the list, else, returns false. Look at the examples below.

String str = list.get(2);
int numberOfElements = list.size();

Let’s take an example program based on the get(), size(), and contains() methods provided by Java ArrayList class.

Example 3:

package arrayListPrograms; 
import java.util.ArrayList; 
public class ArrayListTest { 
public static void main(String[] args) 
  ArrayList al = new ArrayList(); 

// Call get() method using object reference variable 'al' to get the specified element. 
// Since return type of get() method is String, we will store it by using a fruitsName variable with data type String. 
   String fruitsName = al.get(2); 

// Call size() method to get the number of elements present in the list. 
// Since return type of size method is an integer, we will store it by using variable numberOfElements with data type integer. 
   int numberOfElements = al.size(); 

// Check apple element is present or not. 
   boolean check = al.contains("Apple"); 
       [Apple, Orange, Banana, Gauva] 

12. int indexOf(Object o): It is used to get the index of the first occurrence of the specified element, if the element is not present in the list, it returns the value -1.

13. int lastIndexOf(Object o): It is used to get the index of the last occurrence of the specified element in the list. If the element is not present in the list, it returns -1. For example:

int pos = list.indexOf("Apple");
int lastPos = list.lastIndexOf(20);

Let’s take an example based on the indexOf() and lastIndexOf() methods provided by array list.

Example 4:

package ArrayListTest; 
import java.util.ArrayList; 
public class Test { 
public static void main(String[] args) 
  ArrayList<Integer> list = new ArrayList<Integer>(); 
  int pos = list.indexOf(30); 
  int lastPos = list.lastIndexOf(40); 
       [10, 20, 30, 40]

In this example, we have created an ArrayList called “list” that will hold objects of only Integer data type. We then use the add() method to add multiple elements to the ArrayList. We have used the indexOf() and lastIndexOf() methods to get positions of elements.

How do we manually increase or decrease current capacity of ArrayList?

1. ensureCapacity(): This method is used to increase the current capacity of ArrayList. Since the capacity of an array list is automatically increased when we add more elements. But to increase manually, ensureCapacity() method of ArrayList class is used.

2. trimTosize(): The trimTosize() method is used to trim the capacity of ArrayList to the current size of ArrayList. For example:

ArrayList<String> list = new ArrayList<String>(); // Here, list can hold 10 elements.(Default initial capacity).
 list.ensureCapacity(20); // Now it can hold 20 elements.

Advantage of ArrayList in Java

Some advantages of using ArrayList in Java are:

(a) Dynamic size: Unlike arrays, an ArrayList can grow or shrink dynamically, meaning that we do not need to specify its size at the time of declaration.

(b) Easy to use: ArrayList is easy to use and provides a variety of methods for adding, removing, and accessing elements.

(c) Type safety: ArrayList provides type-safety in Java, meaning that we can only add elements of the same data type.

Disadvantage of ArrayList

Some disadvantages of using ArrayList in Java are as follows:

(a) Slow performance: ArrayList can have slow performance when dealing with a large number of elements. This is because it needs to resize the array and copy the elements to the new array every time it exceeds its capacity.

(b) Not thread-safe: ArrayList is not thread-safe in Java, meaning that if multiple threads access the same ArrayList object at the same time, it can lead to data inconsistency or race conditions.

(c) Not suitable for primitive types: ArrayList can only store objects, meaning that we need to use wrapper classes for primitive types, such as Integer for int, Double for double, and so on.

When to Use ArrayList in Java?

ArrayList can be used in a Java application program when

  • we want to store duplicate elements.
  • we want to store null elements.
  • It is more preferred in Java when getting of the element is more as compared to adding and removing elements.
  • we are not working in the multi-threading environment in Java because ArrayList is non-synchronized.

This tutorial has covered almost all important points related to ArrayList in Java with the help of important example programs. I hope that you will have understood ArrayList methods and practiced all example programs. In the next, we will understand enumeration in Java.
Thanks for reading!!!