Site icon TestingDocs.com

What is an ArrayList?

Introduction

ArrayList is a resizable array in Java. It is an implementation of the List interface. Array is fixed in size, whereas ArrayList can grow or shrink dynamically as needed to accommodate adding and removing elements.

Class Diagram

ArrayList is random access list. It supports fast and generally constant access time for the elements. You can add duplicate elements to the list.

Array List is not thread safe. So, if multiple threads access concurrently, and when threads attempt to modify the list, it must be synchronized externally. For example, thread operation that adds or deletes one or more elements in the list.

The list order is maintained while adding and removing elements to the list. For example, when an element is inserted at specified position in the list, the other elements are shifted to the right.

Sample Program

Simple program to add elements to the list is shown below:

import java.util.ArrayList;
import java.util.Scanner;

public class ArrayListExample {
    public static void main(String[] args) {
        Scanner input = null;
        try{
            input = new Scanner(System.in);
            ArrayList<Integer> arrList =new ArrayList<Integer>();
            System.out.println("Add elements to list");
            while(input.hasNextInt()){
                arrList.add(Integer.parseInt(input.nextLine()));
            }

            System.out.println("Input ArrayList is:");

            for (Integer a : arrList) {
                System.out.print("[" + a.intValue() + "]");
            }
        } catch(Exception e){
            e.printStackTrace();
            System.out.println("Unexpected Error...!");
        } finally {
            if (input != null) {
                input.close();
            }
        }
    }
}

 

Run output of the program

 

56
99
65
2
45
56
1
stop
Input ArrayList is:
[56][99][65][2][45][56][1]

Exit mobile version