I have an array of ArrayLists. I'm iterating over them using a variable called 'al' and changing the contents of that arraylist. However, I see that the contents of the original array of ArrayList have changed. Why is this?
I was expecting that since I am only changing the contents of a new variable called 'al', the contents of the original array of ArrayLists, ie alal wouldn't change.
Are these operating on memory directly? What is this concept called, if I would like to read a bit more about it.
package proj;
import java.util.ArrayList;
public class Ask
{
public static void main(String[] args)
{
ArrayList<Integer> myArrayList1 = new ArrayList<Integer>();
myArrayList1.add(1);
myArrayList1.add(1);
myArrayList1.add(1);
ArrayList<Integer> myArrayList2 = new ArrayList<Integer>();
myArrayList2.add(2);
myArrayList2.add(2);
myArrayList2.add(2);
ArrayList<ArrayList<Integer>> alal = new ArrayList<ArrayList<Integer>>();
alal.add(myArrayList1);
alal.add(myArrayList2);
for(ArrayList<Integer> al : alal)
{
al.set(0, 99);
}
System.out.println(alal);
}
}
EDIT : I'm trying to edit my code based on SMA's post so that my contents still remain the same even upon using the set method. This is what I have tried, but my output still reflects the change [[99, 1, 1], [99, 2, 2]]
package proj;
import java.util.ArrayList;
public class Ask
{
public static void main(String[] args)
{
ArrayList<Integer> myArrayList1 = new ArrayList<Integer>();
myArrayList1.add(1);
myArrayList1.add(1);
myArrayList1.add(1);
ArrayList<Integer> myArrayList2 = new ArrayList<Integer>();
myArrayList2.add(2);
myArrayList2.add(2);
myArrayList2.add(2);
ArrayList<ArrayList<Integer>> alal = new ArrayList<ArrayList<Integer>>();
alal.add(new ArrayList<Integer>(myArrayList1));//creating seperate instance of array list with same content as original list
alal.add(new ArrayList<Integer>(myArrayList2));
for(ArrayList<Integer> al : alal)
{
al.set(0, 99);
}
System.out.println(alal);
}
}
EDIT 2 : However, I don't see the same behavior in a normal ArrayList. Here the contents remain as [1, 2, 3] even after editing them to 99 inside the loop. So, are new instances of these variables created here? Aren't they mere references as before?
package proj;
import java.util.ArrayList;
public class Ask
{
public static void main(String[] args)
{
ArrayList<Integer> myArrayList = new ArrayList<Integer>();
myArrayList.add(1);
myArrayList.add(2);
myArrayList.add(3);
for(int element : myArrayList)
{
element = 99;
}
System.out.println(myArrayList);
}
}