×

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

Centered Square Numbers in Java

In this tutorial, we will understand how to check the number is a centered square number. It is one of the prevalent interview questions of IT companies. Firstly, we will...

3 minutes read.

Java Extends keyword

Extends Extends is a keyword which is completely depended on the concept of the inheritance of the java programming language.To understand about of the keyword, we need to learn the concept...

3 minutes read.

Median Of Stream Of Running Integers in Java

An integer array is given to us. Compute the median of the elements traversed so far in the input array. For the sake of simplicity, assume that there are no...

10 minutes read.

Skyline Problem in Java

The skyline of a city is the outer edge of the pattern created by all of its structures when viewed from a distance. Return the skyline that these buildings together...

4 minutes read.

Convert List to String in Java

We occasionally need to create a string from a list of characters. Since a string is only a collection of characters, a character array can be converted into a string....

6 minutes read.

Hourglass problem in Java

In this section, we will discuss the hourglass problem in Java.The aim is to find the largest sum of an hour glass given a 2D matrix. An hour glass is made...

2 minutes read.

Java Boolean equals() method

The equals() method of Java Boolean class returns a Boolean value true if the specified argument is not null and is same as this object, else it returns false. Syntax public boolean...

2 minutes read.

GCD Program in Java

GCD Program in Java The GCD program in Java outputs the GCD of the given numbers. In mathematics, Greatest Common Divisor (GCD), Greatest Common Factor or Highest Common Factor (HCF) of...

14 minutes read.

Insertion Sort in Java

Insertion Sort in Java Insertion sort in Java is a simple sorting algorithm that works in the same way as we hold cards in hand. Insertion sort does the sorting element-by-element,...

3 minutes read.

Fibodiv Number in Java

Before understanding the concept of the fibodiv number, one should realize what the Fibonacci number is. What are Fibonacci Numbers? The Fibonacci sequence of whole numbers is composed of the numbers 0,...

5 minutes read.

Java Integer rotateRight() method

The rotateRight() method of Java Integer class returns the value obtained by rotating the  2’s complement binary representation of the given integer value right by the specified number of bits. Syntax public...

1 minute read.

Cosmic Superclass in Java

The parent class of all Java classes is the Object class. The Java Object class is the parent of all Java classes, whether directly or indirectly. The Object class is...

6 minutes read.

Exception Handling Program in Java

Exception Handling Program in Java Exception means something that is abnormal. In Java, an exception is treated as a problem that disrupts the normal flow of the program. An exception leads...

7 minutes read.

How to make Java Projects

Ant and Maven are both offered by NetBeans for the development of Java applications. When using Ant, the IDE creates an Ant build script depending on the settings you select...

6 minutes read.

Basic Terms in Multithreading

To understand the terms of multithreading, we must have knowledge about concurrency, processes, and threads. Concurrency The concurrency stands for performing multiple tasks at the same time. In the process communication, the operating system permits the process...

8 minutes read.

Grepcode Java util date

What is java.util.Date Class? The date and time in Java are provided through the java.util.Date class. If you imported java.util, it could be helpful. Use the Java.util.Date class to implement this class...

4 minutes read.

Java Boolean compareTo() method

The compareTo() method of Java Boolean class compares the Boolean argument with the Boolean instance and returns integer value, zero, or negative 1, or positive 1 based on the result...

2 minutes read.

Java logger

Logging is a crucial Java feature that aids developers in identifying issues. The logging methodology is included with Java as the programming language. It offers the Logging API, which debuted...

7 minutes read.

Java String Interview Questions

Java String Interview Questions String is the most common and important discussed topics in a Java interview. In Java interview interviewer generally asked three to four questions based on String concept....

16 minutes read.

Java Base64 Encoding and Decoding

Introduction to Encoding and Decoding Encoding is the process of putting the sequence of characters like letters, numbers, punctuations, and other symbols into a specialised format for the efficient transmission or...

11 minutes read.