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
