Skip to content
Related Articles

Related Articles

Can Two Variables Refer to the Same ArrayList in Java?

Improve Article
Save Article
  • Last Updated : 07 Jan, 2021
Improve Article
Save Article

ArrayList class in Java is basically a resize-able array i.e. it can grow and shrink in size dynamically according to the values that we add to it. It is present in java.util package.


ArrayList<E> list = new ArrayList<>();

An ArrayList in java can be instantiated once with the help of the ‘new’ keyword and can be referred to by various objects/variables.

The figure above shows how the object ‘list’ points to the ArrayList inside the memory. Now let us see how we can make another object to point to the same ArrayList that is instantiated above. 

Syntax: Two variables refer to the same ArrayList:

ArrayList<Integer> secondList = list;

Now when assigned the ‘list’ to the ‘secondList’ then the ‘secondList’ also starts pointing to the same ArrayList inside the memory. Notice here simply create a new instance. Now, for a better understanding let’s dive into code and see a few examples.

Below is the implementation of the problem statement:


// Java program to show how two objects can
// refer to same ArrayList in Java
import java.util.ArrayList;
public class GFG {
    public static void main(String[] args)
        // Creating an ArrayList of Integer type in Java
        ArrayList<Integer> list = new ArrayList<>();
        // Creating a new ArrayList object and making it
        // refer to the first ArrayList(list)
        ArrayList<Integer> secondList = list;
        // Inserting some Integer values to the
        // arrayList using list variable/object
        // ArrayList after insertions : [17, 10, 1, 33, 2]
        // Displaying the ArrayList
        System.out.print("ArrayList after insertions: ");
        // Modifying the ArrayList using secondList
        // Removing element from index 0
        // Inserting Integer variables
        // ArrayList after modifications using
        // secondList: [10, 1, 33, 2, 51, 99]
        // Displaying the ArrayList
            "ArrayList after modifications using secondList: ");
    // Function to display an ArrayList
    public static void display(ArrayList<Integer> list)
        for (int i = 0; i < list.size(); i++) {
            System.out.print(list.get(i) + " ");


ArrayList after insertions: 17 10 1 33 2 
ArrayList after modifications using secondList: 10 1 33 2 51 99

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!