Reputation: 3
I have an ArrayList of ArrayList like the following code and I'm intended to add one item to an existed arraylist and save it as well as keeping the old arrayList.
ArrayList<ArrayList<Integer>> bigArr = new ArrayList<ArrayList<Integer>> ();
ArrayList<Integer> arr = new ArrayList<Integer> ();
arr.add(1);
arr.add(2);
arr.add(3);
bigArr.add(arr);
ArrayList<Integer> tt = bigArr.get(0);
tt.add(4);
bigArr.add(tt);
System.out.println(bigArr);
But the thing is that happens is that it prints [[1, 2, 3, 4], [1, 2, 3, 4]] instead of [[1, 2, 3], [1, 2, 3, 4]]. Can someone please tell me what should I do to get the second output?
Upvotes: 0
Views: 140
Reputation: 22972
Object
type parameter's references are pass by value but the memory location that is pointed by them remains same. So changing anything using any reference variable will affect the sameObject
.
So here tt
and arr
is pointing to the same memory location means if you change something in one of them that gets reflected to other as well.
Upvotes: 1
Reputation: 1469
List
s are objects with mutable state. This means that adding or removing items will change the state of the List
your variable is pointing to. You create a single arr = ArrayList<Integer>
, to which you add the values 1, 2, 3
. You then add this list to the bigArr
list of lists. Now, the first element of bigArr
and arr
both point to the same physical object. The moment you retrieve it from bigArr
and store it in the tt
variable, you have three ways to access the same list.
What you want, is a new version (copy) of your initial list at bigArr.get(0)
and add the new value to that list. The easiest way to do this is to use ArrayList
's copy constructor when you retrieve it from the bigArr
. This is already explained in the answer given by Smutje:
ArrayList<Integer> tt = new ArrayList<Integer> (arr);
Upvotes: 0
Reputation: 3820
Because your tt
is still pointing to the same arraylist object. It's modifying the same object.
Solution: Make a new list object by copying old list and add item in that list then add list to main list.
Upvotes: 0
Reputation: 18143
Create two lists instead of reusing the first list.
ArrayList<ArrayList<Integer>> bigArr = new ArrayList<ArrayList<Integer>> ();
ArrayList<Integer> arr = new ArrayList<Integer> ();
arr.add(1);
arr.add(2);
arr.add(3);
bigArr.add(arr);
ArrayList<Integer> tt = new ArrayList<Integer>(arr); // Create a new list based on the elements of the given list
tt.add(4);
bigArr.add(tt);
System.out.println(bigArr);
Upvotes: 2