×

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

Libraries in Java

The Java Class Library (JCL) specifically is a set of dynamically loadable libraries that Java Virtual Machine (JVM) languages can call at any run time, which is fairly significant because...

6 minutes read.

Java OCR

In this article, you will be acknowledged about what is a tesseract OCR, how it works, what are its used and advantages and disadvantages. Also, you will be able to...

4 minutes read.

Vectors in Java

Vector Class We may make resizable arrays comparable to the ArrayList class using the Vector class, which implements the List interface. A vector is similar to a dynamic collection that can...

4 minutes read.

Difference between JDK, JRE and JVM In Java

In the Java ecosystem, three primary components are often mentioned: JDK, JRE, and JVM. Here’s a breakdown of each: Java Development Kit (JDK) The Java Development Kit (JDK) is a comprehensive software...

2 minutes read.

Java vs DotNET

Before understanding the differences between DotNET and Java, one must know about Java and DotNET. Java Java is a general-purpose programming language that is class-based and object-oriented, with minimal implementation dependencies. Regardless of...

9 minutes read.

Java Linters

When it comes to programming, everyone makes mistakes. Errors are bad for developers since they are difficult to handle. But handling as many as possible errors will bring out the...

6 minutes read.

Java String equalsIgnoreCase() method

equalsIgnoreCase() method compares two Strings based on the their content but ignore the case. Syntax public boolean equalsIgnoreCase(Objects anObject) Parameter anObject: Object to be compared with the current String without case consideration. Returns It returns true...

1 minute read.

Check whether a Number is a Power of 4 or Not in Java

There are many ways to figure out if an integer is a power of 4. This section will go over a variety of techniques for figuring out whether or not...

11 minutes read.

History and Evolution of Java

Java is invented by James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and Mike Sheridan at Sun Microsystems, Inc. in 1991. Java is related to C++, which is inherited from...

3 minutes read.

Fibonacci Series Program in Java

Fibonacci Series Program in Java using Recursion Fibonacci series is a series whose every term is comprised of adding its previous two terms, barring the first two terms 0 and 1....

3 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.

Java Math decrementExact() Method

The decrementExact() method of Math class returns the argument which is decremented by one, throwing an exception is the result overflows an int or long. Syntax: public static int decrementExact (int a) Parameters: The...

1 minute read.

Array Slicing in Java

Array slicing is a method in Java for obtaining a subarray of a specified array. Assume a[] is an array. It contains eight items indexed from a[0] to a[7].a[] =...

3 minutes read.

Multiple Inheritance Programs in Java

A component of the object-oriented notion known as multiple inheritances allows a class to inherit properties from multiple parent classes. When methods that have the same signature are present in...

4 minutes read.

How to increment and decrement date using Java?

Before understanding how to increment and decrement the date, one must know about the Calendar class in Java. The Java calendar class offers methods for converting dates between a given moment...

3 minutes read.

Thread Safety and How to Achieve it in Java

Before diving into the topic, let’s just recap the concept of Multithreading provided by Java where we can create and execute multiple threads of the same object. When these multiple...

5 minutes read.

Java Program to Add Digits Until the Number Becomes a Single Digit Number

We will develop Java programme that increase a number's digit count in order to reduce it to one. The issue is also known as the digit root problem. Example Consider the case where...

3 minutes read.

Client Server Program in Java

Client Server Program in Java The client and server are the two main components of socket programming. The client is a computer/node that request for the service and the server is...

7 minutes read.

Interleaving string in Java

If the string Str3 contains all of the characters from Str1 and Str2, it is considered interleaving Str1 and Str2. Keep in mind that the order of all characters in...

5 minutes read.

Java LinkedList

LinkedList Java The Java LinkedList is used to store the elements by using a doubly linked list. It contains the duplicate items, also maintains the order of the insertion, the class...

5 minutes read.