×

ArrayList Program in Java

ArrayList Program in Java: In Java, ArrayList is a class that belongs to java.util package. It is the dynamic list that grows or shrinks at run-time as per the requirements. Because of its dynamic nature, an ArrayList is preferred over a primitive array. In other words, an ArrayList is the resizable array. The ArrayList class implements the List interface and inherits the AbstractList class.

Key Features of an ArrayList

The key features of an ArrayList are:

  • Duplicate elements are allowed in the ArrayList.
  • ArrayList maintains the insertion order of elements added to it.
  • ArrayList is not synchronized.
  • Like a primitive array, elements can be accessed randomly based on their index.

If we want to create an ArrayList, we need to create an instance of the ArrayList class.

ArrrayList<type> identifier = new ArrayList<type>();

In the above statement, identifier is the reference variable. Its name can be changed as per one’s choice. type in the angular brackets ensures what kind of array list is going to be created. For the creation of an integer list, Integer should be used inside the angular brackets. For the creation of a string list, String should be used, and so on.

FileName: ArrayListExample.java

 // Importing class ArrayList
import java.util.ArrayList;
public class ArrayListExample
{
// driver method
public static void main(String argvs[])
{
    // creating an array list of integer type
    ArrayList<Integer> al = new ArrayList<Integer>();
    // adding elements to the list
    al.add(1);
    al.add(-9);
    al.add(45);
    al.add(443);
    al.add(4);
    // calculating the size of the list
    int size = al.size();
    if(size > 0)
    {
        // displaying the size and the elements of the list
        System.out.println("Size of the array list is: " + size );
        System.out.println(al );
    }
}
} 

Output:

 Size of the array list is: 5
[1, -9, 45, 443, 4] 

Explanation: In the code, we have created an empty list. The add() method appends an element to the list. Thus, the add() method increases the size of the list by one. Eventually, we are printing the list on the console.

Iterating an ArrayList

There are many ways to iterate over an ArrayList.  A few of them are:

  • Using for-loop
  • Using an iterator

Let’s start with the for-loop.

Using For-Loop

Consider the following program.

FileName: ArrayListExample1.java

 // Importing class ArrayList
import java.util.ArrayList;
public class ArrayListExample1
{
// driver method
public static void main(String argvs[])
{
    // creating an array list of integer type
    ArrayList<Integer> al = new ArrayList<Integer>();
    // adding elements to the list
    al.add(1);
    al.add(-9);
    al.add(45);
    al.add(443);
    al.add(4);
    // calculating the size of the list
    int size = al.size();
    System.out.println("Elements of the array list are: " );
    // Iterating on every elements of the list
    for(int i = 0; i < size; i++)
    {
       System.out.println(al.get(i) );
    }
}
} 

Output:

 Elements of the array list are:
1
-9
45
443
4 

Explanation: After adding the elements to the list, we are calculating the size of the list. Then, using a Java for-loop, we are iterating over the elements of the lists. The get() method is used to access the elements of the list. It returns the element present at the given index. Thus, get(0) returns the element present at the index 0.  get(1) is responsible for accessing the element present at the index 1, and so on.

Using an Iterator

Consider the following program.

FileName: ArrayListExample2.java

 // Importing the class ArrayList
import java.util.ArrayList;
// Importing the class Iterator
import java.util.Iterator;
public class ArrayListExample2
{
// driver method
public static void main(String argvs[])
{
    // creating an array list of integer type
    ArrayList<Integer> al = new ArrayList<Integer>();
    // adding elements to the list
    al.add(1);
    al.add(-9);
    al.add(45);
    al.add(443);
    al.add(4);
    // calculating the size of the list
    int size = al.size();
    System.out.println("Elements of the array list are: " );
    // Creating an iterator for the list al
    Iterator itr = al.iterator();
    //check if the list has elements 
    while(itr.hasNext() )
    {  
        //printing the element and move to the next
        System.out.println(itr.next()); 
    }
}
}              

Output:

 Elements of the array list are:
1
-9
45
443
4 

Explanation: Instead of a for-loop, we have used an iterator to iterate the elements of the ArrayList. The hasNext() method checks elements are present in the list or not. If elements are presented in the ArrayList, it returns true, else returns false. The next() method returns the next element that is getting printed on the console.

Removing Elements from an ArrayList

To remove the elements from an ArrayList, the remove() method is used. Observe the following program.

FileName: ArrayListExample3.java

 // Importing the class ArrayList
import java.util.ArrayList;
// Importing the class Iterator
import java.util.Iterator;
public class ArrayListExample3
{
// driver method
public static void main(String argvs[])
{
    // creating an array list of integer type
    ArrayList<Integer> al = new ArrayList<Integer>();
    // adding elements to the list
    al.add(7);
    al.add(8);
    al.add(9);
    al.add(17);
    al.add(25);
    // removing the element present at the index 2
    al.remove(2);
    System.out.println("Elements of the array list are: " );
    // Creating an iterator for the list al
    Iterator itr = al.iterator();
    //check if iterator has the elements 
    while(itr.hasNext() )
    {  
        //printing the element and move to the next
        System.out.println(itr.next()); 
    }
}
} 

Output:

 Elements of the array list are:
7
8
17
25 

Explanation: Before the deletion of elements, the array list looked like the following.

ArrayList Program In Java

When the element at the 2nd index is deleted, the elements that followed element 9 get shifted towards the left by one place.

ArrayList Program In Java

Thus, the removal of an element from an array list is a lengthy process because shifting of elements from their original position takes time.


Related Topics

How to sort an array in Java

Sorting is the process of arranging the elements of a list or array in a specific order, either ascending or descending. The sorting criterion numerical and alphabetical is commonly used...

6 minutes read.

Display List of TimeZone with GMT and UTC in Java

It is vital to establish the right TimeZone in Java code when working with dates for Daylight Saving Time. In this part, we will present the time zones with GMT. TimeZone Those...

5 minutes read.

Self-Descriptive Numbers in Java

A number n is given. Identifying the self-descriptive numbers that exist between 1 and n is our task. Self-Descriptive Numbers The definition of a self-descriptive number, m, is a number with b...

6 minutes read.

RMI program in Java

Remote Method Invocation is what it stands for. An object can call the method of another object in a different space address using the RMI API, which may be on the...

3 minutes read.

Generic queue in Java

Before understanding how to implement a generic queue in java, one must know about generics and queue in java. Generics in Java Generics are parameterized types. The goal is to enable type...

6 minutes read.

Pernicious Number in Java

If the number of 1s in a number appearing in the binary representation is the prime number, such a number is known as a pernicious number. A pernicious number always corresponds to...

4 minutes read.

Polymorphism Program in Java

Polymorphism Program in Java: Polymorphism means the existence of different forms of an object. The object can be a class object or a real-time entity. For example, a person can...

5 minutes read.

Concurrent Modification Exception In Java

When an object is attempted to be updated concurrently when it is not allowed, the ConcurrentModificationException arises. This error typically occurs while using Java Collection classes. When another thread is iterating...

5 minutes read.

Transient variable in Java

In this article, you will be acknowledged about transient variable along with its functions. We would conclude by understanding an example program about it. Transient variable By introducing the transitory keyword, we...

3 minutes read.

Java Print Writer

PrintWriter: It is used to write output data from the file. It is the class of Java.io package. It inherits the properties of the Writer class. Writer Class: It is a class of...

4 minutes read.

Buffer reader to read string in Java

The Buffered Reader class of Java is used to read the stream of characters from the input stream. Program to read string using Buffer reader import java.io.*; class  Demo {   public static void main(String...

3 minutes read.

Minimum Window Subsequence in Java

In this article, you will be very well acknowledged about the minimum window subsequence, what is the approach and how it is implemented. The example program is also executed and...

4 minutes read.

Hashtable in Java

Hashtable in Java The Hashtable class implements the Map interface and extends the Dictionary class. It implements a hash table which shows the key-value relation, i.e., it maps the keys to the values....

9 minutes read.

Minimum Lights to Activate Java Snippet Class

Minimum Lights to Activate Problem in Java In prison, there is a hallway that is N units long. Given an N-dimensional array A. If the light at the ith position is...

3 minutes read.

Java Char Keyword

The java char keyword is a data type which is defined as character data type.Char keyword belongs to a primitive data type where the data types are classified into primitive...

4 minutes read.

Find the Frequency of Each Element in the Array in Java

We may count the occurrence of each element in the array of items. Maintaining one array to store the counts of each array element is one strategy for solving this issue....

3 minutes read.

Java throws

Java throws: The Java throws keyword is used with the signature of the method to indicate that the method may raise an exception. The method that uses the Java throws...

3 minutes read.

Use Of Adapter class in Java

An adapter class in Java enables listener interfaces to be implemented by default. The Delegation Event Model is where the idea of listener interfaces first appeared. It is one of...

3 minutes read.

Streams in Java

The conventional Java SE 8 version came with many new peculiarities, out of which the most striking of which are assuredly lambda expressions and the method references. Streams and Streams...

14 minutes read.

public static void main string args meaning in java

In java main() method is the initial point for execution of the program. If a program doesn’t contain the main method, the program will not execute. JVM(java virtual machine) starts...

3 minutes read.