Scientech Easy Use of ArrayList in Java with Programs | Scientech Easy

Saturday, November 10, 2018

Use of ArrayList in Java with Programs

In this tutorial, we will learn the use of ArrayList in Java with programs in an easy way. The use of ArrayList is very important to understand because interviewer often asks the freshers one question-related to the use of the array list in the interview. So let's start first with a small introduction of ArrayList

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

An array list can be used when
➤ We want to add duplicate elements in the list. The ArrayList class allows duplicate elements. Let's see a simple example program.
Program source code 1:
    package com.arraylisttest; import java.util.ArrayList; import java.util.Iterator; public class DuplicateElementsExample { public static an void main(String[] args) { // Create an array list with an initial capacity of 10. ArrayList<String> al=new ArrayList<String>(); // 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 the duplicate elements 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

➤ The size of the list is growable. Suppose we have a series of elements in a program that we need to handle on the 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. 
Program source code 2:
    package com.arraylisttest; import java.util.ArrayList; public class GrowableArrayListExample { 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); } }
See the below picture.
ArrayList use in Java
A conceptual view of adding elements in the list

    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]
➤ We want to store null element in the list. We can add any number of null elements.
Program source code 3:
    package com.arraylisttest; import java.util.ArrayList; import java.util.Iterator; public class NullTestExample { public static void main(String[] args) { // Creates an array list with an initial capacity of 10. ArrayList<String> arlist=new ArrayList<String>(); 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<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
➤ When the getting of the elements is more as compared to adding and removing of elements, the ArrayList is more preferred as compared to LinkedList because ArrayList implements 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 com.arraylisttest; import java.util.ArrayList; public class GettingElementsExample { 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
➤ We are not working in the multithreading environment in the Java because array list is not synchronized. Due to which multiple threads can access the same array list object simultaneously. To make the array list as synchronized, we will have to use Collections.synchronizedList() method.  
Program source code 5:
    package com.arraylisttest; 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<Integer> list=new ArrayList<Integer>(); // Create multiple thread class objects m1, m2 and passes the 'list' as a parameter. MultiThreadEx m1=new MultiThreadEx(list); MultiThreadEx m2=new MultiThreadEx(list); // Call the start() method to start the thread using m1 and m2 reference variable. m1.start(); m2.start(); try { // Call join() method to complete the task of adding elements in the array list. 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
As you can see in the above example program, ArrayList instance is sharing between two threads class objects m1 and m2. Each thread is trying to add 6 elements in the array list. Since ArrayList is not synchronized. Therefore, the expected output is unpredictable. When we run the above code, it shows the size of the array list 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 the main thread started the thread-1, thread-1 inserted an element 0(i.e i=0) in the list. After adding the element 0, thread-1 went for sleep(50). Since we are using join() method to complete the task of adding elements from 0 to 6 by m1 but when the thread-1 went 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 up, thread-1 again entered into the running state and added the element 1 (i.e i=1) in the list, After adding, it went for the sleep(50). 
After the sleeping time over, it again entered into the running state to insert element 2. After adding, thread-1 again went for sleep(50), meanwhile, the main thread started the thread-2 and thread-2 added an element 2 which is unpredictable. 

Thus, you can see the effect of using ArrayList in the multithreading environment. Therefore, ArrayList is not thread-safe when the multiple threads access the same array list object. 
Note: If you run this program on your system, maybe you will get different unpredictable output. 

Final word 
I hope that this article will help you to understand the use of ArrayList in Java with example programs. All programs are basic but important to clear the concepts. So practice all these programs in your laptop.

Popular