'I'm filling up an ArrayList of ArrayList<Integer> type . The insertion is done twice but the result reflects only the second update. Explain
ArrayList<ArrayList<Integer>> list = new ArrayList<>();
int i=0;
ArrayList<Integer> l = new ArrayList<>();
l.add(1);
l.add(4);
list.add(i,l);
i++;
l.clear();
l.add(0);
l.add(4);
l.add(3);
l.add(2);
list.add(i,l);
Now my list has 2 elements with same value of {0,4,3,2} . What happens to {1,4} ?
Solution 1:[1]
Here is what is going on. list contains a reference to l. So when you clear l, you clear the one you added to list. But the reference is still there to accept new values.
ArrayList<ArrayList<Integer>> list = new ArrayList<>();
int i=0;
ArrayList<Integer> l = new ArrayList<>();
l.add(1);
l.add(4);
list.add(i,l);
i++;
l.clear(); // you just deleted all the contents of list `l` but not the list `l` itself.
l.add(0);
l.add(4);
l.add(3);
l.add(2); // now list `l` (the reference still in `list` contains 0,4,3,2
list.add(i,l); // and now list contains the same reference yet again so you get
System.out.println(list);
prints
[[0, 4, 3, 2], [0, 4, 3, 2]]
And note that if you do this, list.get(0).set(1,99) will affect both lists because each List l in List list is a reference to the same list.
[[0, 99, 3, 2], [0, 99, 3, 2]]
Solution 2:[2]
The answer of WJS is correct.
Just if you wonder how to make it work the way that you expect:
ArrayList<ArrayList<Integer>> list = new ArrayList<>();
int i=0;
ArrayList<Integer> l = new ArrayList<>();
l.add(1);
l.add(4);
list.add(i,l);
i++;
l = new ArrayList<>(); //Remove l.clear(); and add new instance of the ArrayList
l.add(0);
l.add(4);
l.add(3);
l.add(2);
list.add(i,l);
Not to be confusing it is better you to make a new declaration with new name like:
ArrayList<ArrayList<Integer>> list = new ArrayList<>();
int i=0;
ArrayList<Integer> listFirst = new ArrayList<>();
listFirst.add(1);
listFirst.add(4);
list.add(i,listFirst);
i++;
ArrayList<Integer> listSecond = new ArrayList<>();
listSecond.add(0);
listSecond.add(4);
listSecond.add(3);
listSecond.add(2);
list.add(i,listSecond);
System.out.println(list);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Level_Up |
