Can Two Variables Refer to the Same ArrayList in Java?
ArrayList class in Java is basically a resizable 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.
Syntax:
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
import java.util.ArrayList;
public class GFG {
public static void main(String[] args)
{
ArrayList<Integer> list = new ArrayList<>();
ArrayList<Integer> secondList = list;
list.add(17);
list.add(10);
list.add(1);
list.add(33);
list.add(2);
System.out.print("ArrayList after insertions: ");
display(list);
secondList.remove(0);
secondList.add(51);
secondList.add(99);
System.out.print(
"ArrayList after modifications using secondList: ");
display(list);
}
public static void display(ArrayList<Integer> list)
{
for (int i = 0; i < list.size(); i++) {
System.out.print(list.get(i) + " ");
}
System.out.println();
}
}
|
OutputArrayList after insertions: 17 10 1 33 2
ArrayList after modifications using secondList: 10 1 33 2 51 99
Last Updated :
05 Jan, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...