java - A List, anyone can answer -


public static void main(string[] args) {     list<list<integer>> list = new arraylist<list<integer>>(); // final list     list<integer> l = new arraylist<integer>(); // l list     list<integer> m = new arraylist<integer>(); //  m list     list<integer> temp = new arraylist<integer>();      l.add(1);     l.add(2);     l.add(3); // list l       m.add(4);     m.add(5);     m.add(6); // list m       temp.addall(l); // add l temp     list.add(temp);     system.out.println("temp: "+temp);     system.out.println("list: "+list);       temp.addall(m); // add m temp1     list.add(temp);     system.out.println("temp: "+temp);     system.out.println("list: "+list); } 

the result is

temp: [1, 2, 3] list: [[1, 2, 3]] temp: [1, 2, 3, 4, 5, 6] list: [[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6]] 

i think should be:

temp: [1, 2, 3] list: [[1, 2, 3]] temp: [1, 2, 3, 4, 5, 6] list: [[1, 2, 3], [1, 2, 3, 4, 5, 6]] 

why last list [[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6]]?

i rename temp1 temp in order compiled correctly.

this because when first execute "list.add(temp);"

list gets reference temp. when content of temp changed, content of list gets changed.

public static void main(string[] args) {     list<list<integer>> list = new arraylist<list<integer>>(); // final list     list<integer> l = new arraylist<integer>(); // l list     list<integer> m = new arraylist<integer>(); //  m list     list<integer> temp = new arraylist<integer>();      l.add(1);     l.add(2);     l.add(3); // list l       m.add(4);     m.add(5);     m.add(6); // list m       temp.addall(l); // add l temp1     list.add(temp); // list references temp. when content of temp changed, content of list gets changed.     system.out.println("temp: "+temp);     system.out.println("list: "+list);        temp.addall(m); // add m temp. content of temp changed, content of list     list.add(temp);      system.out.println("temp: "+temp);     system.out.println("list: "+list); } 

Comments