1
List<List<Integer>> list = new LinkedList<List<Integer>>();
List<Integer> tmp = new LinkedList<Integer>();
tmp.add(2);
list.add(tmp);
tmp.add(3);
list.add(tmp);

The result of list is [[2,3],[2,3]]; I just confused about that why it is not [[2],[2,3]]. And when I use list.add(new LinkedList<Integer>(tmp)) it will work. I print tmp, it is still [2], [2,3], it is not changed. Why that happen? Thank you in advance.

Bahramdun Adil
  • 5,907
  • 7
  • 35
  • 68
codemonkey
  • 331
  • 1
  • 4
  • 16
  • 2
    Because both two elements of list refer to the same object temp. If you want the result [[2],[2,3]], you can create new another tmp object. – Anh Nguyen Ngoc Mar 24 '16 at 01:51
  • In the current code, you have only instantiated `tmp` a single time, so it it is added to `list` twice, but it is the same object. – KevinO Mar 24 '16 at 01:52

2 Answers2

3

You added a reference to tmp to list. When you added it, tmp only contained [2,3]. After the addition to list, you added 3 to the same reference of tmp. This caused both "copies" to have [2,3].

One way could be to create a new list and do the following

tmp = new LinkedList<Integer>();
tmp.add(3);
list.add(tmp);

Now, list will look like [[2],[3]].

If you want list to be [[2],[2,3]]...

List<List<Integer>> list = new LinkedList<List<Integer>>();
List<Integer> tmp = new LinkedList<Integer>();
tmp.add(2);

// add a copy of this linkedlist to the "BIG" list
list.add(new LinkedList<Integer>(tmp));
tmp.add(3);
list.add(tmp);

let me know if something is not clear.

Debosmit Ray
  • 5,228
  • 2
  • 27
  • 43
0

Java uses references to objects that you create with new to refer to those objects. In this example, the variable tmp is actually a reference to the LinkedList object on the heap.

Since list is a list of objects, it is actually a list of references to those objects. In this case, its two elements are references to the same heap object, tmp.

Stewart Smith
  • 1,396
  • 13
  • 28