Sufia
Sufia

Reputation: 3

Add Item to the ArrayList of ArrayList

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

Answers (4)

Akash Thakare
Akash Thakare

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 same Object.

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.

enter image description here

Upvotes: 1

jhkuperus
jhkuperus

Reputation: 1469

Lists 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

Deepu--Java
Deepu--Java

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

Smutje
Smutje

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

Related Questions