简体   繁体   中英

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?

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);

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.

在此处输入图片说明

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM