×

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

Packages in Java

Packages in Java can be defined as an assortment for grouping various classes and interfaces based on their performance. It is a catalog for holding various java files. They provide...

4 minutes read.

How to Change the Day in the Date using Java?

To operate with the date and time in Java, we need the Calendar abstract class. It provides a number of helpful interfaces that enable us to convert dates between a...

4 minutes read.

Java Math cosh() Method

The cosh() method of Math class returns the first hyperbolic cosine((e+e)/2) of a double value. Syntax: public static double cosh(double x) Parameters: The parameter ‘x’ represents the number whose hyperbolic cosine is to be...

2 minutes read.

Transaction Management in java

Definition: A database application is an application that is running against a relational database and executes one or more transactions. A transaction is an executing program that contains some database operations,...

4 minutes read.

How to check Date is Greater in Java?

In this article, you will be acknowledged about how to check if the given date is greater than the other date or not. We are simply comparing the dates and...

7 minutes read.

Java Type Casting

Type casting is a technique or process used in Java to convert one data type into another, either manually or automatically. The compiler performs the automatic conversion, and the programmer...

3 minutes read.

Diffie Hellman Algorithm in Java

In this section, you will be acknowledged about Diffie Hellman algorithm clearly step wise along with an example and also an example program. Diffie Hellman Algorithm One of the most significant algorithms...

3 minutes read.

Why main method is static in Java

The method serves as the entry point for Java programmes or simply the point from which the programme begins to run. As a result, it is one of the most...

4 minutes read.

How Many Ways to Create an Object in Java?

As you know, a class is a blueprint for an object, and you can create objects from it. There are several ways to create objects of classes in Java. This...

6 minutes read.

Tetris Game in Java

The Tetris game is among the most well-known video games ever produced for computers. Today, we may engage in this game on a mobile device as well. Alexey Pajitnov conceptualized...

12 minutes read.

flour pack problem in Java

Create a method called canPack and give it three int parameters: bigCount, smallCount, and objective. The bigCount option indicates the number of large flour bags (5 kilos each). The smallCount argument indicates...

3 minutes read.

Set Value to Enum in Java

In this article, you will be acknowledged about Enum in java. Most importantly you will learn how to set value to Enum or how to practically customize a value to...

3 minutes read.

Method chaining in Java

Method chaining in Java is the act of calling a series of methods one after the other. The sole distinction between it and function Object () constructor chaining is the difference...

3 minutes read.

Difference between Abstract Class and Interface

There is a similarity between abstract class and interface is that we cannot create objects for both of them. But irrespective of this, there are some differences between them, let’s...

2 minutes read.

Uses of Java

Java is used in many real-world Java applications, including technologies and tools. This Java programming language has become the backbone for developing many applications. In areas like embedded systems and...

3 minutes read.

Prepared statement in Java

Prepared statement: A prepared statement is a statement that is pre-compiled SQL statement, and it is a sub-interface of a statement. Compared to other statement objects in java, Prepared Statement objects have...

3 minutes read.

Tree Implementation in Java

Introduction to Tree A non-linear, hierarchical data structure called a "tree" is made up of a number of nodes, each of which contains a values and a sequence of pointers to...

14 minutes read.

Iccanobif Numbers in Java

In this article, you will be very well equipped with the knowledge of iccanobif numbers in Java. You will also know how they are formed and basic example programs on...

3 minutes read.

Magic Square in Java

A square with numbers is referred to as a magic square. The numbers in a magic square of order n are arranged to ensure that the sum of all of...

4 minutes read.

Java Integer toHexString() method

The toHexString() method of Java Integer class returns a string representing the specified int argument as an unsigned integer in base 16. Syntax public static String toHexString (int  i)  Parameters The parameter ‘i’ represents...

1 minute read.