×

Java ArrayList

Java ArrayList Class

A Java ArrayList class is a dynamic array which is used to store the elements. It is a part of collection framework. It implements the List Interface and inherits the AbstractList class.

The benefit of using ArrayList over a standard array is that, in a standard array, we are able to store only a fixed number of elements. Java ArrayList also allows us to access the list randomly.

Java ArrayList comprises of both constructors and methods. Following are some constructors and methods along with their usage.

Constructors of ArrayList :

ArrayList() It creates an empty ArrayList with a default capacity of 10. Syntax: ArrayList<E> myArray= new ArrayList<E>();
ArrayList(Collection c) It creates a list containing the elements of the specified collection. Syntax: public boolean addAll(collection c)
ArrayList(int Capacity) It creates an empty ArrayList of specified capacity in the parameter. Syntax: ArrayList myArray= new ArrayList(int Capacity);

Example to use constructors:

import java.util.*;
public class Constructor
{
public static void main(String args[])
{
//first create ArrayList of type string
ArrayList>String> a= new ArrayList>String>();
int counter=0;
for (String s:a)
{
counter++;
}
System.out.println("No Arguments:"+counter);
//we don't have any element in the ArrayList, so when we try to print the counter value it will not retain any value.
//we will create one more ArrayList and initialize the capacity to that.
ArrayList>String> b=new ArrayList>String>(20);
counter=0;
for (String s:a)
{
counter++;
}
System.out.println("No Arguments with capacity:"+counter);
System.out.println();
//If we try to print the counter it won't print because we initialize capacity and also the value of the counter will not increase.
//Now, again we create the ArrayList with the elements
String sArray[]= {"Java", "Android", "Kotlin", "Python"};
List list= Arrays.asList(sArray);
ArrayList c=new ArrayList(list);
c.add("PL/SQL");//it will append the element to the list
//using advance for loop
for(String s:c)
System.out.println("ArrayList c element"+s);
System.out.println(c); 

Output:

No Arguments:0
No Arguments with capacity:0
ArrayList c element :Java
ArrayList c element :Android
ArrayList c element :Kotlin
ArrayList c element :Python
ArrayList c element :PL/SQL
[Java, Android, Kotlin, Python, PL/SQL] 

Methods of Java ArrayList:

Modifier And Type Methods Usage
Boolean add (E a) It is used to add an element to the end of the list
addAll(Collection c) It is used to add all of the elements in the specified collection to the end of the list. And it is added in the order that they returned from the specified collection's iterator.
addAll(int index, Collection c) It will insert all the elements at the specified index position in the specified collection into the list.
Contains(Object o) If the list contains the specified elements, it will return true.
isEmpty() If the list is blank, it will return true.
remove(Object o) If the specified element is present, then the first occurrence of that element will be removed from the list.
removeAll(Collection c) It will remove all the elements of the list from the specified collection.
retainAll(Collection c) It continues to hold only the elements in the list contained in the specified collection.
int indexof(Object o) It will return -1 if the list is blank or returns the index number for the first occurrence of the specified component in the list.
lastIndexOf(Object o) It will return the index of the last occurrence of the specified element in the list, or -1 if the list is empty.
size() It gives the number of elements in the list.
void add(int index, E element) It is used to insert a specific element at the specified position in the ArrayList.
clear() It will remove all elements from the list.
ensureCapacity(int minCapacity) The capacity of the ArrayList will be increased to ensure that it holds the minimum number of elements specified in the minCapacity argument.
trimToSize() It will trim the capacity of the ArrayList to the list's current size.
Object[ ] clone() It will return a shallow copy of the ArrayList instance.
toArray() Will return an array containing all elements in the list in proper sequence(First to Last).
Iterator<E> iterator() It will return an iterator over the element in the list in the sequence.
ListIterator<E> listIterator() Will return a listIterator over the element in the list(in sequence)
listIterator(int index) Will return a listIterator over the element in the list from the specified index.
List<E> subList(int fromIndex, int toIndex) Returns the element from the list between the specified index value.
abstract<E> get(int index) It will return the element from the specified index in the list.
E remove(int index) It removes the element from the specified position in the list.
E set(int index, E element) It will replace the element from the specified position in the list with the specified element in the argument.

Advantages of ArrayList over Array:

  • The length of the ArrayList is variable.
  • The size of the ArrayList can be modified dynamically.
  • The ArrayList can traverse in both directions.
  • We can add different types of data in an ArrayList if we do not use generics.

Example to add, remove, clone, and clear the elements in the ArrayList.

import java.util.ArrayList;
public class Arraylist {
       public static void main(String[] args)
       {
              // we will see how to add elements
              ArrayList al=new ArrayList();
              Object cloneList;
              al.add("Android");
              al.add("Java");
              al.add("Arrays");
              System.out.println("Size of arraylist:"+ al.size());//It will show the size               of the array
              System.out.println("Content of al:"+al);//It will show the contents of the array
              al.remove("Java");//It will remove java from the list
              System.out.println("Size of arraylist after deletion:"+al.size());
              System.out.println("Content of al:"+al);//prints content after deletion
              cloneList=al.clone();//It will clone the present element in the list
              System.out.println("Elements in the cloned list are:"+cloneList);
              al.clear();//It will clear the ArrayList
              System.out.println("Arraylist after clear:"+al);
       }
} 

Output:

Size of arraylist:3
Content of al:[Android, Java, Arrays]
Size of arraylist after deletion:2
Content of al:[Android, Arrays]
Elements in the cloned list are:[Android, Arrays]
Arraylist after clear:[] 

Example to illustrate addAll(Collection c)

import java.util.*;
import java.io.*;
class ArrayListDemo
{
    public static void main (String[] args)
    {
      //Creating an empty array list1
      ArrayList<String> arrlist1 = new ArrayList<String>(5);//capacity=5
      //now using add method to add elements in the list
       arrlist1.add("Java");
       arrlist1.add("Python");
       arrlist1.add("Hadoop");
       // It prints all the elements available in list1
       System.out.println("Printing list1:");
       for (String subject : arrlist1) 
             System.out.println("Subjects = " + subject);          
       // creating another empty array list2
       ArrayList<String> arrlist2 = new ArrayList<String>(5);
       //add() method to add elements in list2
       arrlist2.add("Android");
       arrlist2.add("CPP");
       arrlist2.add("R programming");
       arrlist2.add("CCNA");
       //Printing all the elements available in list2
       System.out.println("Printing list2:");
       for (String subject : arrlist2) 
        System.out.println("Subjects = " + subject);        
       // inserting all elements then list 2 will get printed after list 1
       arrlist1.addAll(arrlist2);
       System.out.println("Printing all the elements");
       //Printing all the elements available in list1  
       for (String subject : arrlist1) 
             System.out.println("Subjects = " + subject);
    }
} 

Output:

Printing list1:
Subjects = Java
Subjects = Python
Subjects = Hadoop
Printing list2:
Subjects = Android
Subjects = CPP
Subjects = R programming
Subjects = CCNA
Printing all the elements
Subjects = Java
Subjects = Python
Subjects = Hadoop
Subjects = Android
Subjects = CPP
Subjects = R programming
Subjects = CCNA 

Example to illustrate addAll(int index, Collection c)

import java.io.*;
import java.util.*;
   class ArrayListdemo {
       public static void main(String args[])
       {
       // creating an empty array list1
       ArrayList<String> arrlist1 = new ArrayList<String>(5);//capacity 5
       //To add elements in the list,using add() method
       arrlist1.add("Jammu and Kashmir");
       arrlist1.add("Himachal Pradesh");
       arrlist1.add("Punjab");
       // prints all the elements available in list1
       System.out.println("Printing list1:");
       for (String state : arrlist1)
             System.out.println("State = " + state);        
       // creating an empty array list2
       ArrayList<String> arrlist2 = new ArrayList<String>(5);//capacity 5
       //To add elements in list2, using add() method
       arrlist2.add("Delhi");
       arrlist2.add("UP");
       arrlist2.add("Bihar");
       arrlist2.add("Gujarat");
       // prints all the elements available in list2
       System.out.println("Printing list2:");
       for (String state : arrlist2)
             System.out.println("State = " + state);        
       // inserting all elements of list2 at fourth position
       arrlist1.addAll(3, arrlist2);
       System.out.println("Printing all the elements");
       // prints all the elements available in list1
       for (String state : arrlist1)
             System.out.println("State = " + state);        
       }
} 

Output:

Printing list1:
State = Jammu and Kashmir
State = Himachal Pradesh
State = Punjab
Printing list2:
State = Delhi
State = UP
State = Bihar
State = Gujarat
Printing all the elements
State = Jammu and Kashmir
State = Himachal Pradesh
State = Punjab
State = Delhi
State = UP
State = Bihar
State = Gujarat 

Example to demonstrate the working of contains() method in ArrayList.

import java.util.*;
class StudentContains {
       public static void main(String[] args)
       {
       // creating an Empty String ArrayList
       ArrayList<String> arr = new ArrayList<String>(5);//Capacity 5
       // using add() method to initialize values
       arr.add("Ankit");
       arr.add("Aman");
       arr.add("Vikash");
       arr.add("Himanshu");
       arr.add("Anubhav");
       // using contains() to check if the student Aman is present or not
       boolean ans = arr.contains("Aman");
       if (ans)
             System.out.println("Student Aman is present");
       else
             System.out.println("Aman is not present");
       // using contains() to check if Anubhav is present or not.
       ans = arr.contains("Akshay");
       if (ans)
             System.out.println(" Akshay is present");
       else
             System.out.println("Anubhav is not present");
       }
} 

Output :

Student Aman is present
Anubhav is not present 

Example to demonstrate the working of isEmpty() method in ArrayList

import java.util.*;
class CheckEmpty {
       public static void main(String[] args)
       {
       // creating an Empty ArrayList
       ArrayList<String> arr = new ArrayList<String>(20);
       // checking, list is empty or not
       boolean ans = arr.isEmpty();
       if (ans == true)
             System.out.println("The ArrayList is empty");
       else
             System.out.println("The ArrayList is not empty");
       // adding an element to the ArrayList
       arr.add("Tutorials And Example");
       // checking, list is empty or not
       ans = arr.isEmpty();
       if (ans == true)
             System.out.println("The ArrayList is empty");
       else
             System.out.println("The ArrayList is not empty");
       }
} 

Output:

The ArrayList is empty
The ArrayList is not empty 

Example to demonstrate the working of indexOf in ArrayList

import java.util.*;
class IndexOfExample {
public static void main(String[] args) {
// creating an Empty Integer ArrayList
ArrayList<Integer> roll = new ArrayList<Integer>(10);
 // using add() to initialize and add values
 roll.add(1);
 roll.add(2);
 roll.add(3);
 roll.add(4);
 roll.add(5);
  roll.add(6);
  // printing initial value of ArrayList
  System.out.print("The initial values in ArrayList are : ");
for (Integer value : roll) {
System.out.print(value);
  System.out.print("  ");
  }  
// using indexOf() to find index of 4
int position =roll.indexOf(4);
//printing index of element 4
  System.out.println("\nThe no. 4 is at index : " + position);
}
}

Output:

The initial values in ArrayList are : 1 2 3 4 5 6
The element 4 is at index : 3 

Example to demonstrate the working of  lastIndexOf() and size() method in ArrayList.

import java.util.*;
class LastIndexExample {
                public static void main(String[] args)
                {
                // creating an Empty ArrayList
                ArrayList<String> ar = new ArrayList<String>(10);
                // using add() to initialize values
                ar.add("A");
                ar.add("A");
                ar.add("B");
                ar.add("C");
                ar.add("D");
                ar.add("A");
                ar.add("K");
                ar.add("B");
                ar.add("A");
                ar.add("K");
                System.out.println("The list initially " + ar);
                int size = ar.size();
// printing the size of array list
               System.out.println("Size of list = " + size);
                // printing last index of A
                int element = ar.lastIndexOf("A");
                if (element != -1)
               System.out.println("the lastIndexof of A is " + element);
                else
               System.out.println("A is not present in the list");
                // printing last index of B
                element = ar.lastIndexOf("B");
                if (element != -1)
               System.out.println("The lastIndexof of B is" + element);
                else
               System.out.println("B is not present in the list");
                 }
} 

Output:

The list initially [A, A, B, C, D, A, K, B, A, K]
Size of list = 10
the lastIndexof of A is 8
The lastIndexof of B is7 

Example to illustrate add(int index, Object element):

import java.io.*;
import java.util.*;
class ArrayListExample {
public static void main(String[] args)
                {
                // Initializing an empty array list
                ArrayList<Integer> arlist = new ArrayList<Integer>(5);
                // using add() to add elements in the list
                arlist.add(10);
                arlist.add(5);
                arlist.add(15);
                // adding element 50 at 1st position
                arlist.add(0, 50);
                // printing all the elements available in list
                for (Integer num : arlist) {
               System.out.println("No. = " + num);
                }
                }
} 

Output:

No. = 50
No. = 10
No. = 5
No. = 15 

Example to demonstrate  ensureCapacity() method:

import java.util.*;
class CapacityDemo {
                public static void main(String[] args) throws Exception
                {
                try {
               // Initializing object of ArrayList<Integer>
               ArrayList<String> arlist = new ArrayList<String>();
               // add element to array list
               arlist.add("A");
               arlist.add("B");
               arlist.add("C");
               arlist.add("D");
               // Printing the ArrayList
               System.out.println("ArrayList: "+ arlist);
               // ensure that the ArrayList can hold upto 200 elements using ensureCapacity() method
               arlist.ensureCapacity(200);
               // Prints
               System.out.println("ArrayList can store upto 200 elements.");                      
                }
                catch (NullPointerException e) {
               System.out.println("Exception : " + e);
                }
                }
} 

Output:

ArrayList: [A, B, C, D]
ArrayList can store upto 200 elements. 

Example to demonstrate the working of  trimTosize() method in ArrayList.

import java.util.*;
class trimExamp {
                public static void main(String[] args)
                {
                // creating an Empty ArrayList
                ArrayList<Integer> ar = new ArrayList<Integer>(10);
                // using add() to add values
                ar.add(20);
                ar.add(11);
                ar.add(8);
                ar.add(60);
                ar.add(25);
                // trims the size of array to the number of elements
                ar.trimToSize();
                int size = ar.size();
                // printing the size of array list
               System.out.println("Size of list = " + size);
                System.out.println("Numbers in the list are:");
                // printing all the elements
                for (Integer num : ar) {
               System.out.println("Number = " + num);
                }
                }
} 

Output:

Size of list = 5
Numbers in the list are:
Number = 20
Number = 11
Number = 8
Number = 60
Number = 25 

Example to demonstrate working of Objectp[] toArray().

import java.io.*;
import java.util.*;
class ToArrayDemo
{
                public static void main (String[] args)
                {
                //initializing array list
                List<Integer> li = new ArrayList<Integer>();
                li.add(1);
                li.add(2);
                li.add(3);
                li.add(4);
                Object[] objects = li.toArray();
                // Prints array of objects
                for (Object obj : objects)
               System.out.print(obj + " ");
                }
} 

Output:

1 2 3 4

Example to demonstrate listIterator() method

import java.util.*;
class ListIteratorDemo {
                public static void main(String[] args) throws Exception
                {
                try {
               // Creating object of ArrayList<String>
               ArrayList<String> arlist = new ArrayList<String>();
               //now adding elements to the ArrayList
               arlist.add("Java");
               arlist.add("Spring");
               arlist.add("Boot");
               arlist.add("Hibernate");
               // Printing ArrayList
               System.out.println("ArrayList: "+ arlist);
               // Creating object of ListIterator
               // now using listIterator() method
               ListIterator<String> iterator = arlist.listIterator();
               // Printing the iterated values
               System.out.println("\nUsing ListIterator:\n");
               while (iterator.hasNext()) {
               System.out.println("Value is : "+ iterator.next());
               }
                }
                catch (NullPointerException e) {
               System.out.println("Exception thrown : " + e);
                }
                }
} 

Output:

ArrayList: [Java, Spring, Boot, Hibernate]
Using ListIterator:
Value is : Java
Value is : Spring
Value is : Boot
Value is : Hibernate 

Example to demonstrate subList() method

import java.util.*;
class sublistDemo {
                public static void main(String[] args) throws Exception
                {
                try {
               // Creating object of ArrayList
               ArrayList<String> arlist = new ArrayList<String>();
               // adding elements to arlist1
               arlist.add("Java");
               arlist.add("Python");
               arlist.add("Android");
               arlist.add("IOS");
               arlist.add("IOT");
               // printing ArrayList
               System.out.println("Original arraylist: "+ arlist);
               // getting the subList using subList() method
               List<String> arlist2 = arlist.subList(2, 4);
               // printing the subList
               System.out.println("Sublist of arraylist: "+ arlist2);
                }
                catch (IndexOutOfBoundsException e) {
               System.out.println("Exception : " + e);
                }
                catch (IllegalArgumentException e) {
               System.out.println("Exception : " + e);
                }
                }
} 

Output:

Original arraylist: [Java, Python, Android, IOS, IOT]
Sublist of arraylist: [Android, IOS] 

Example to demonstrate the working of  get() method in ArrayList

import java.util.*;
                class GetDemo
                {
                public static void main(String[] args)
                {
                // creating an Empty Integer ArrayList
                ArrayList<Integer> num = new ArrayList<Integer>(4);
                // using add() method to initialize values
                num.add(5);
                num.add(2);
                num.add(9);
                num.add(1);
                System.out.println("List: " + num);
                //using get() to fetch element from index 2   
                int element = num.get(3);
                System.out.println("Element at index 3 is " + element);
                }
} 

Output:

List: [5, 2, 9, 1]
Element at index 3 is 1 

Example to demonstrate set() method

import java.util.*;
class SetExample {
                public static void main(String[] args) throws Exception
                {
               try {
              // Creating object of ArrayList<Integer>
               ArrayList<String> arrlist = new ArrayList<String>();
               // adding elements to arraylist
               arrlist.add("Java");
               arrlist.add("Spring");
               arrlist.add("Struts");
               arrlist.add("MongoDB");
               arrlist.add("Oracle");
               // printings ArrayList
               System.out.println("Before operation: "+ arrlist);
               // Replacing element at the index 3 with Hibernate using set()
               String i = arrlist.set(3, "Hibernate");
               // Print the modified arrlist
               System.out.println("After operation: "+ arrlist);
               // Print the Replaced element
               System.out.println("Replaced element: "  + i);                      
                }
                catch (IndexOutOfBoundsException e) {
               System.out.println("Exception thrown: " + e);
                }
                }
} 

Output:

Before operation: [Java, Spring, Struts, MongoDB, Oracle]
After operation: [Java, Spring, Struts, Hibernate, Oracle]
Replaced element: MongoDB 

Related Topics

Hashing Algorithm in Java

The hashing algorithm is a method that maps data to the fixed-length hash. The Java hash-based algorithm employs a cryptographic mathematical operation. A hash technique or hash function is supposed...

8 minutes read.

Statements in java

What is Statement in java: A statement in java is an instruction that explains what will happen based on the condition. Types of java statements: There are different statements in java Expression statementDeclaration statementControl...

2 minutes read.

Minimum Number of Platforms Required for a Railway Station

The train station problem is one of the most significant problems typically posed in the programming round interview to gauge a candidate's aptitude for logic and problem-solving. Problem of Railway Station The...

6 minutes read.

Operators in Java

There is a good operator environment provided by Java. These operators are divided into four different groups i.e. arithmetic, bitwise, relational, and logical. There are other operators also available to...

7 minutes read.

Best Java IDE

Applications for desktop, workplace, smartphone, and the internet can be created using Java, one of the most popular programming languages. Java will undoubtedly be a popular programming language for so...

5 minutes read.

Synchronized Keyword in Java

Synchronization is the process of limiting access to a shared resource or data to a single thread at a given moment in time. This aids in shielding the data from...

6 minutes read.

Java Math abs() Method

The abs() method of Math class returns the absolute value of the argument where the argument can be int, double, float, long. Syntax public static int abs(int a) public static float abs(float a) public...

2 minutes read.

How to Concatenate Two Strings in Java

How to Concatenate Two Strings in Java Concatenation of two strings means adding the beginning of one string to the end of the other string. Some of the ways to concatenate...

3 minutes read.

Non-primitive data types in Java

The kind of data stored in the variable is determined by its type. The type describes the data category (different sizes and values). These are not already built into the devices....

4 minutes read.

Stack vs Heap in Java

In Java, whenever we declare an object or create a variable, whether it is an instance variable, local variable, or static variable, a certain memory is used to store the...

4 minutes read.

Set Matrix Zeros in Java

In coding round interviews, it is frequently asked as the most significant challenge. an m*n matrix is provided. Set the entire column and row of the matrix to 0 if any...

6 minutes read.

How to Convert int to long in Java

How to Convert int to long in Java When two variables of different types are involved in the single expression, Java compiler uses built-in library function to convert the variable to...

2 minutes read.

Java Math sin() Method

The sin() method of Java Math class returns the trigonometric sine of the specified angle. Syntax: public static double sin(double a) Parameters: The parameter ‘a’ represents an angle measured in radians. Return Value: The sin() method...

1 minute 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.

Java Map Interface

A map is a collection that maps keys to values, with no duplicate keys allowed. The elements in a map are key/value pairs. HashMap: HashMap stores the keys in a...

3 minutes read.

Bully Algorithm code in Java

Election algorithms include the bully algorithm, mainly used to select a coordinate. To find a coordinator in a distributed system that can carry out the tasks required by other processes,...

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.

Counting sort in Java

An array's elements are sorted using the counting sort method, which counts how many times each distinct element appears in the array. The count is kept in an auxiliary array,...

3 minutes read.

Types of Assignment Operators in Java

In this tutorial, we are going to study assignment operators and their types in Java language. Before proceeding to the types, let us know the term ‘assignment operator’.  The assignment...

5 minutes read.

Creating a Custom Generic Class in Java

To indicate parameter types when creating generic classes, we utilize the <> symbol. The syntax used to generate objects of a generic class is as follows. // To create an instance...

4 minutes read.