Can Two Variables Refer to the Same ArrayList in Java?
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:
ArrayList after insertions: 17 10 1 33 2 ArrayList after modifications using secondList: 10 1 33 2 51 99
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.