×

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 generate random numbers in Java

Random numbers, also known as fake numbers, are actually a part of a very large sequence, so they are called random numbers. In a defined set of numbers, every number...

6 minutes read.

How to compare dates in Java

Introduction: In Java, dates can be compared using a similar interface's compareTo() technique. This method returns 'zero' if each date is the same, returns a rate "more than 0" if...

6 minutes read.

Why String in Immutable in Java?

Why String in Immutable in Java Immutable means unchangeable or unmodifiable.  Strings in Java are immutable, it means once a string is created, it cannot be modified or changed. Any change...

2 minutes read.

How to set path in Java

To make programs that can run on our systems, we need to install programming language-related software in our systems. Different programming languages require different types of software, aka IDEs (Integrated Development...

5 minutes read.

Three-way operator in Java

The ternary operator in Java is the only conditional operator that takes three operands. It's a popular one-line substitute for the if-then-else expression among Java programmers. If-else clauses can be...

3 minutes read.

String Concatenation in Java

In Java, it gathers a new String that combines several strings. Following are the manners to concatenate strings in Java: By + (String concatenation) operatorBy concat() method By + (String concatenation) operator Java...

4 minutes read.

What is anagram in Java?

In this section will explain what an anagram is in Java and demonstrate how to determine whether or not a text is an anagram. In Java interviews, the anagram Java...

4 minutes read.

Getter and Setter Method in Java Example

In Java programming, getter and setter methods are often employed. The values of class fields can be accessed and changed using Java's getter and setter methods. A private access specifier...

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

Swing Program in Java

Java Swing is part of Java Foundation Classes (JFC). The swing toolkit is used to generate Graphical User Interface (GUI) for programs written in Java. The Java swing API is...

4 minutes read.

Java time local date

Java: Java is one of the programming language which is object oriented. It consists of many features such as robust, simple, architecture neutral, dynamic, distributed, multi threaded, portable etc. The main feature...

3 minutes read.

InputMismatchException in Java

What is InputMismatchException? One of the most frequent errors in Java is the InputMismatchException. Because the InputMismatchException is a subtype of the java.lang, it is an unchecked exception. RuntimeException.Because it is...

4 minutes read.

Display Unique Rows in a Binary Matrix in Java

To solve this problem, we must first locate and display the distinct rows of a supplied binary matrix afterward. We will go through how to show distinct rows inside a...

12 minutes read.

FizzBuzz Program in Java

FizzBuzz is a well-known children's game. This game helps children learn division. The FizzBuzz game is becoming a popular programming question, appearing frequently in Core Java interviews. This section will...

3 minutes read.

Difference between C, C++, java

C Language: C language is a procedure oriented language. It has been invented by Dennis Ritchie in the year 1970. It is one of the computer programming language. The purpose of...

3 minutes read.

Java Logo

Java is a prominent and extensively used object-oriented programming language. In 1995, Sun Microsystems created it. Later in 2009, Oracle Corp takeover Java. History of Java Logo The name of the island...

3 minutes read.

Creating a Jar file in Java

The JDK's jar (Java Archive) tool offers the ability to produce jar files that can be executed. If you double-click a jar file that is executable, it will call the...

2 minutes read.

Java Extends vs Implements

Java: We known that the java is a pure object oriented programming language. Java programming language consists of many features such as portable, plat form independence, secured, robust, simple, architecture neutral,...

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

Chromatic Number in Java

The chromatic number is the bare minimum of colours necessary to accurately colour any graph. To put it another way, the chromatic number can be thought of as the bare...

6 minutes read.