Realtime Use of ArrayList in Java with Example

We have familiarized that an ArrayList is the most basic type of collection in Java. It uses an array internally to store data when we add elements to the array list.

The ArrayList class automatically manages the size of the array when we add an element to the array list.

When the underlying array is fixed, ArrayList class automatically creates a new array with a larger size or capacity and copies all the existing elements to the new array before adding the new elements.

The old array of the collection will be gone in the garbage collection. Now, we will understand realtime use of ArrayList in Java with example program. That is, when to use ArrayList in Java application.

ArrayList can be used in Java Application when


1. We want to add duplicate elements to the list. Since Java ArrayList class allows duplicate elements, we can add duplicate elements to the list.

Let’s take an example program where we will use ArrayList to add duplicate elements in the list.

Program code 1:

package arrayListProgram; 
import java.util.ArrayList; 
import java.util.Iterator; 
public class DuplicateElementsEx 
{ 
public static void main(String[] args) 
{ 
// Create an ArrayList with an initial capacity of 10. 
   ArrayList<String> al = new ArrayList<String>(); 

// Adding elements to the list. 
    al.add("A"); // Adding element at index 0.
    al.add("B"); // Adding element at index 1.
    al.add("C"); // Adding element at index 2.
    al.add("D"); // Adding element at index 3.
   System.out.println("Original insertion array list order: " +al);

// Adding a duplicate element at position 2 and end of the list. 
   al.add(2, "B"); 
   al.add("A"); 
   System.out.println("After adding duplicate element, ArrayList insertion order "); 

// Call iterator() method to iterate over the elements of the array list. 
   Iterator<String> itr = al.iterator(); 
   while(itr.hasNext())
   { 
     String str = itr.next(); 
     System.out.println(str); 
   } 
  } 
}
Output: 
       Original insertion array list order: [A, B, C, D] 
       After adding duplicate element, ArrayList insertion order 
       A B B C D A

2. One of the biggest advantages of ArrayList is that the size of ArrayList is growable in nature. It can change the size at runtime. We don’t need to worry about the initial size of the ArrayList or how many elements can it hold. Suppose we have a series of elements in a program that we need to handle on a dynamic basis.


Sometimes, this series of elements can be 5, or sometimes, it can be 3 or 8. i.e. size is growable. So, in this case, you can use ArrayList.

Let’s take an example program based on the growable nature of ArrayList.

Program code 2:

package com.arraylisttest; 
import java.util.ArrayList; 
public class GrowableArrayListEx 
{ 
public static void main(String[] args) 
{ 
// Create an array list with an initial capacity of 6. 
   ArrayList<Integer> al = new ArrayList<Integer>(6); 
    al.add(10); 
    al.add(20); 
    al.add(30); 
    al.add(40); 
    al.add(50); 
    al.add(60); 
  System.out.println(al); 

  Integer sizelist = al.size(); 
  System.out.println("Original size: " +sizelist); 

// Since the initial capacity of array list is full, 
// Therefore, when we add a new element to the list, its capacity is automatically grown by 50%. 
    al.add(70); 
    al.add(80);  
    Integer size = al.size(); 
    System.out.println("After adding new elements, ArrayList's size: " +size); 

    al.remove(6); 
    System.out.println(al); 
   } 
}

Explanation: 

Look at the below figure to understand better how ArrayList grows its capacity internally.

How to use ArrayList in Java

Output: 
       [10, 20, 30, 40, 50 60] 
       Original size: 6 
       After adding new elements, ArrayList's size: 8 
       [10, 20, 30, 40, 50, 60 80]

3. We want to store null elements on the list. We can add any number of null elements in ArrayList.


Let’s take an example program where we will add null elements in the list using ArrayList. Look at the source code.

Program code 3:

package arrayListProgram; 
import java.util.ArrayList; 
import java.util.Iterator; 
public class NullTestEx
{ 
public static void main(String[] args) 
{ 
// Creates an ArrayList with an initial capacity of 10. 
   ArrayList<String> arlist = new ArrayList<String>(); 
   
   arlist.add("Ganga"); 
   arlist.add("Yamuna"); 
   arlist.add(null); // Adding null element. 
   arlist.add("Godavari"); 
   arlist.add("Ganga"); // Adding duplicate element. 
   arlist.add(null); // Adding null element.
   System.out.println("Original order: " +arlist); 
  
  Iterator<String> itr = arlist.iterator(); 
  while(itr.hasNext())
  { 
     System.out.println(itr.next()); 
  } 
 }
Output: 
       Original order: [Ganga, Yamuna, null, Godavari, Ganga, null] 
       Ganga Yamuna null Godavari Ganga null

4. Getting elements from the list is more than compared to adding and removing elements. In this case, ArrayList is more preferred as compared to LinkedList because ArrayList implements a random access interface.

The retrieval of elements is very slow in LinkedList due to traverse from the beginning or ending to reach the element.

Program code 4:

package arrayListProgram; 
import java.util.ArrayList; 
public class GettingElementEx 
{ 
public static void main(String[] args) 
{ 
  ArrayList<String> al = new ArrayList<String>(); 
   al.add("a"); 
   al.add("ab"); 
   al.add("abc"); 
   al.add("abcd"); 
   al.add("a"); 
  System.out.println(al); 

// Call get() method using reference variable al to get elements. 
   System.out.println("Getting element from position 0 to 4 "); 
   for(int i = 0; i < = 4 ; i++)
   { 
     String getElement = al.get(i); 
     System.out.println(getElement); 
   } 
  String getE = al.get(3); // Randomly getting element from position 3. 
  System.out.println("Getting element at position 3: " +getE); 
 } 
}
Output: 
       [a, ab, abc, abcd, a] 
       Getting element from position 0 to 4 
       a ab abc abcd a 
       Getting element at position 3: abcd

5. We are not working in the multi-threading environment in Java applications because ArrayList is not synchronized. Due to which multiple threads can access the same ArrayList object simultaneously.

To make ArrayList as synchronized, we will have to use Collections.synchronizedList() method.

Program code 5:

package arrayListProgram; 
import java.util.ArrayList;
public class MultiThreadEx extends Thread 
{ 
// Declare ArrayList variable. 
   ArrayList<Integer> list; 

// Create a one parameter constructor with parameter 'list' and type ArrayList. 
   MultiThreadEx(ArrayList<Integer> list)
   { 
     this.list = list; 
   } 
@Override 
public void run()
{ 
  System.out.println("Run method"); 
  for(int i = 0 ; i < = 6; i++)
  { 
// Adding elements in the list. 
   list.add(i); 
   try { 
// Call sleep() method to delay some time. 
     Threan ad.sleep(50); 
   }
   catch(InterruptedException e)
   { 
     e.printStackTrace(); 
   } 
  } 
} 
public static void main(String[] args) 
{ 
// Creates an ArrayList object with an initial capacity of 10. 
   ArrayList<Ineger> list = new ArrayList<Integer>(); 

// Create multiple thread class objects m1, m2 and passes 'list' as a parameter. 
   MultiThreadEx m1 = new MultiThreadEx(list); 
   MultiThreadEx m2 = new MultiThreadEx(list); 

// Call start() method to start thread using m1 and m2 reference variable. 
    m1.start(); 
    m2.start(); 
   try { 
// Call join() method to complete the task of adding elements in the ArrayList. 
     m1.join(); 
     m2.join(); 
   } 
   catch (InterruptedException e) 
   { 
      e.printStackTrace(); 
    } 
Integer sizelist = list.size(); 
System.out.println("Size of list is " + sizelist); 
for(Integer i : list)
{ 
 System.out.println("num - " + i); 
} 
 } 
}
Output: 
       Run method 
       Run method 
       Size of list is 12 
       num - 0 
       num - 0 
       num - 1 
       num - 2 
       num - 2 
       num - 3 
       num - 3 
       num - 4 
       num - 4 
       num - 5 
       num - 5 
       num - 6

Explanation:

As you can observe in the preceding example program, ArrayList instance is sharing between two threads of class objects m1 and m2. Each thread is trying to add 6 elements to ArrayList. Since ArrayList is not synchronized.

Therefore, the expected output is unpredictable. When we run the above code, it shows the size of the ArrayList is 12 (not 14). Element 1 and 6 are inserted only one time in the list.

Let’s see what happened in the above program.

(a) When thread-1 is created from the main thread, it inserts an element 0 in the list. After adding element 0 in the list, thread-1 goes to sleep position.

Since we are using join() method to complete the task of adding elements from 0 to 6 by m1, so when the thread-1 will go for the sleep, meanwhile, the main thread will start thread-2 for execution and will add an element 0 in the list.

(b) When the sleep time of thread-1 is over, thread-1 will again enter into the running state and add element 1 in the list. After adding, it will again go to sleep position.

(c) After sleeping time over, it again entered into the running state to insert element 2. After adding, thread-1 will again enter into sleep. Meanwhile, the main thread will again start thread-2 to complete its task and add element 2 which is unpredictable.

As you can observe in the program that the use of ArrayList in the multi-threading environment does not provide thread safety. This is because ArrayList is not synchronized.

For more detail of Thread synchronization with diagram: Thread synchronization in Java


Note: If you run this program on your system, may be you will get different unpredictable output.


There are several advantages of using an ArrayList, such as dynamic size, flexibility, and easy to use. In this tutorial, you have learned the top 5 realtime use of ArrayList in Java application. Hope that you will have understood the basic points of when ArrayList is useful in Java applications.
Thanks for reading!!!
Next ⇒ Store user-defined class object in ArrayList⇐ PrevNext ⇒

Please share your love