ArrayList Tutorial With Examples In JAVA

ArrayList is a dynamic data structure in which you can add or remove any number of elements and those elements are stored in ordered sequence. It may also contain duplicate values.

ArrayList are the implementations of List interface. The package you required to import the ArrayList is import java.util.ArrayList;

Important Note: In ArrayList, the items to be added are only of object type. No primitive data types (i.e. int, char etc) are allowed to insert in ArrayList.


Syntax of ArrayList:

Its very easy to use ArrayList, below is the syntax to declare it:

ArrayList arrayListDemo = new ArrayListDemo();

String ArrayList Declaration:

ArrayList<String> arrayListDemo = new ArrayListDemo<String>();

By using this syntax, an ArrayList is created which you can use to store characters. Here arrayListDemo is the name of this particular ArrayList.


ArrayList Methods:

ArrayList is a subclass of AbstractList class and it implements List Interface. It has various methods that are defined and inherited from its parent class. Below is the list of those methods with example:

1. boolean add(Object o):

  • It adds an element of Specific Object type at the end of Arraylist as no index is mentioned in the method.
  • It returns True if element is successfully added, and returns false if it is not.

The Example program of this boolean add(Object o) method is as:

import java.util.ArrayList;

public class ArrayListMethods {

public static void main(String[] args) {
    
    //Integer ArrayList
ArrayList<Integer> aList = new ArrayList<Integer>();

aList.add(5);
aList.add(11);
aList.add(17);

System.out.println("Integer Number Added in ArrayList= " + aList);

//String ArrayList
ArrayList<String> sList = new ArrayList<String>();

sList.add("Learning");
sList.add("JAVA");

System.out.println("String Added in ArrayList= "+ sList);


}

}

Output:

Integer Number Added in ArrayList= [5, 11, 17]
String Added in ArrayList= [Learning, JAVA]

2. void clear():

This method remove all the elements of the arraylist.

Below the example program clear() method shows the working of this method:

import java.util.ArrayList;

public class ArrayListMethods {

    public static void main(String args[]) {

        ArrayList<Integer> aList = new ArrayList<Integer>();

        // use add() method to add elements in the list
        aList.add(1);
        aList.add(2);
        aList.add(3);

        // let us print all the elements available in aList

        System.out.println("Printing aList items before using clear method= "+aList);
        System.out.println("Printing size of aList1= " + aList.size());

        //using clear method

        aList.clear();
        System.out.println("Printing aList element after using clear method= "+aList);
        System.out.println("size of aList1 after clear() method= " + aList.size());

    }
}

Output:

Printing aList items before using clear method= [1, 2, 3]
Printing size of aList1= 3
Printing aList element after using clear method= []
size of aList1 after clear() method= 0

3. Object clone():

This method returns the exact same copy of the arraylist object.

Below example helps us to understand this method easily:

import java.util.ArrayList;

public class ArrayListMethods {
    public static void main(String args[]) {

        ArrayList<String> aList1 = new ArrayList<String>();

        // use add() method to add elements in the list

        aList1.add("A");
        aList1.add("B");
        aList1.add("C");
        aList1.add("D");

        //Using clone() method to copy aList1 into a new aListCopy Arraylist

        ArrayList<String> aListCopy = (ArrayList<String>) aList1.clone();

        System.out.println("aListCopy elements copied from aList1= "+aListCopy);

    }
}

Output: 

aListCopy elements copied from aList1= [A, B, C, D]

4. boolean contains(Object element):

This method returns true if the calling ArrayList object contains the specific element as given in the argument list, otherwise it returns false.

Below is the example program of boolean contains(Object element) method is as:

import java.util.ArrayList;

public class ArrayListMethods {

    public static void main(String args[]) {

        ArrayList<Integer> aList = new ArrayList<Integer>();

        // use add() method to add elements in the list

        aList.add(7);
        aList.add(2);
        aList.add(9);

        //Checking contains method

        boolean flag1 =  aList.contains(2);
        if (flag1 == true) {
            System.out.println("aList contains element 2");
        }else{
            System.out.println("aList doesn't contains element 2");
        }

        boolean flag2 = aList.contains(5);

        if (flag2 == true) {
            System.out.println("aList contains element 5");
        } else{
            System.out.println("aList doesn't contains element 5");
        }


    }

}

Output:

aList contains element 2
aList doesn't contains element 5

Read: List Of All ArrayList Methods


ArrayList Example In Java:

Example 1: ArrayList of Pre Definded Data types:

Let us discuss ArrayList with the help of program, In this program we have created two objects that store predefined data types that are of Integer and String type, following program is divided into 3 steps that are discussed below:

import java.util.*; 


public class ArrayListDemo{ 
 
 public static void main(String args[]){ 
 
 //Step 1: Creating Objects of ArrayList
 ArrayList<String> arraylist1= new ArrayList<String>();
 ArrayList<Integer> arraylist2= new ArrayList<Integer>();

 //Step 2: Adding Values 
 arraylist1.add("This");
 arraylist1.add("is");
 arraylist1.add("String");
 arraylist1.add("arraylist");
 
 arraylist2.add(1);
 arraylist2.add(2);
 arraylist2.add(3);
 arraylist2.add(4);
 
 //Step 3: Displaying all the values
 System.out.println("String ArrayList : " +arraylist1);
 System.out.println("Integer ArrayList : " +arraylist2);
 } 
}

Output:

String ArrayList : [This, is, String, arraylist]
Integer ArrayList : [1, 2, 3, 4]

Explanation of Example:

  • In Step 1, we have created two objects of ArrayList Class, first object stores value of String type, Second of Integer type.
  • In Step 2, we have used add method to store values in the data structures that we have created in step 1.
  • In Step 3, we have displayed values of these objects.

Example 2: ArrayList Of User-Defined Objects:

We have discussed ArrayList example with Pre Defined Data types like Integer and String types, now let us discuss Arraylist of User Defined Class.

Now, Let us take a Class Student that has two properties its Name and Age. What we will do is, we will create different student objects and store them in the ArrayList as shown in the following program.

import java.util.*;

//Step 1: Created a Class that have values name and age

class Student{
private int age;
private String name;

//Step 2: Creating Constructor of Student class
public Student( String name, int age) {
this.age = age;
this.name = name;
}

//Step 3: Getting and Setting the values
public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

//Step 4: Gives meaning to the object

@Override

public String toString() {

return "Student [name=" + name + ", age=" + age + "]";

}
}

Creating the main class ArrayListDemo:

import java.util.*;
//Step 5: Creating the main class

public class ArrayListDemo{

public static void main(String args[]){

//Step 6: Creating objects of Student class

Student student1= new Student("Vikas" , 24);
Student student2= new Student("Arun" , 23);
Student student3= new Student("Rahul" , 25);


//Step 7: Creating an object of ArrayList and adding Student objects

ArrayList<Student> arrayStudent = new ArrayList<Student>();

arrayStudent.add(student1);
arrayStudent.add(student2);
arrayStudent.add(student3);

//Step 8: Displaying the values

for(Student student: arrayStudent){

System.out.println(student);
}
}
}

Output:

Student [name=Vikas, age=24]
Student [name=Arun, age=23]
Student [name=Rahul, age=25]

Description:

  • In Step 1, we have created a class Student , that defined two parameters name and age.
  • In Step 2, we have created constructor of Student class, that will assign values of name and age when we define the object in main class.
  • In Step 3, we have used getter and setter methods to set and get the values of name and age.
  • In Step 4, toString() method has been overridden, to give meaning to the object,  so that when we print the object using System.out.println, we can see which object it really is.
  • In Step 5, we have created the main class.
  • In Step 6, we have created three objects of Student Class, and given values to them.
  • In Step 7, an object of ArrayList that is of type Student is created and above created objects has been added into them.
  • In Step 8, All the values has been displayed.

Importance of ArrayList:

  • You can define ArrayList as re-sizable array. It means size of the ArrayList is not fixed, it can grow and shrink dynamically.
  • In ArrayList elements can be inserted at or deleted from a particular position.
  • If generics are not used, ArrayList can hold any type of objects.
  • You can traverse an ArrayList in both the directions – forward and backward using ListIterator
  • ArrayList can hold multiple null and duplicate elements.
  • ArrayList provide sufficient methods to work with like Add().

Quick Revision Points Of ArrayList:

  • ArrayList is dynamic data structure in which you can add or remove any number of elements.
  • The package you required to import the ArrayList is import java.util.ArrayList;
  • AddAll method is having the special feature to add up the all elements of one list to the other.

ArrayList Vs Array: Which To Use When:

Another important thing about ArrayList is when to use it or when to use simple Array? Now as you know ArrayList is dynamic in nature which means you can add or delete the elements with no fixed lower limit and upper limit. So in those situation where you are not sure about the number of elements you should use ArrayList. And where you are clear with the exact size of elements you can use Array. This is because array is fixed in size after its declaration and ArrayList is resizable in nature.