Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How to use ArrayList in Java with Example

In this tutorial, we will learn how to use Arraylist in Java with example programs. 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, the 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.

Use of ArrayList in Java with Example Program


An ArrayList can be used in Java program when,
1. We want to add duplicate elements in the list. The ArrayList class allows duplicate elements.

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

package arrayListProgram; 
import java.util.ArrayList; 
import java.util.Iterator; 
public class DuplicateElementsEx 
{ 
public static an void main(String[] args) 
{ 
// Create an ArrayList with an initial capacity of 10. 
   ArrayList al = new ArrayList(); 
// Adding elements in the list. 
    al.add("A"); 
    al.add("B"); 
    al.add("C"); 
    al.add("D"); 
   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 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. The size of ArrayList is growable in nature. 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 an array list. 

Let’s take an example program based on the growable nature of ArrayList.
Program source 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 al = new ArrayList(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.

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 element on the list. We can add any number of null elements in ArrayList.

Program source 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 arlist = new ArrayList(); 
   arlist.add("Ganga"); 
   arlist.add("Yamuna"); 
   arlist.add(null); // null element. 
   arlist.add("Godavari"); 
   arlist.add("Ganga"); // duplicate element. 
   arlist.add(null); 
  System.out.println("Original order: " +arlist); 
  Iterator 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 of elements is more as compared to adding and removing elements, 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 element.

Program source code 4:

package arrayListProgram; 
import java.util.ArrayList; 
public class GettingElementEx 
{ 
public static void main(String[] args) 
{ 
  ArrayList al = new ArrayList(); 
   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 
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 multithreading environment in Java 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 source code 5:

package arrayListProgram; 
import java.util.ArrayList;
public class MultiThreadEx extends Thread 
{ 
// Declare ArrayList variable. 
   ArrayList list; 
// Create a one parameter constructor with parameter 'list' and type ArrayList. 
   MultiThreadEx(ArrayList list)
   { 
     this.list = list; 
   } 
@Override 
public void run()
{ 
  System.out.println("Run method"); 
  for(int i = 0 ; i  list = new ArrayList(); 
// 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 in 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.

When main thread started thread-1, thread-1 inserted an element 0 in the list. After adding the element 0, thread-1 went in sleep. 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 started thread-2 and added an element 0 in the list.

When the sleep time of thread-1 is over, thread-1 again entered into the running state and added element 1 in the list. After adding, it will again go to sleep position.

After sleeping time over, it again entered into the running state to insert element 2. After adding, thread-1 again went for sleep. Meanwhile, the main thread started the thread-2 and thread-2 added element 2 which is unpredictable. 

Thus, you can understand the effect of using ArrayList in the multithreading environment. Therefore, ArrayList is not thread-safe when multiple threads access the same ArrayList object. 

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

Final words
Hope that this tutorial has covered important points to understand how to use ArrayList in Java with example programs. I hope that you will have understood the use of ArrayList in Java and enjoyed topic.
Thanks for reading!!!

Next ⇒ Store user-defined class object in ArrayList⇐ PrevNext ⇒

The post How to use ArrayList in Java with Example appeared first on Scientech Easy.



This post first appeared on Scientech Easy, please read the originial post: here

Share the post

How to use ArrayList in Java with Example

×

Subscribe to Scientech Easy

Get updates delivered right to your inbox!

Thank you for your subscription

×