2015-09-26 45 views
-1
public static void main(String[] args) { 
    List<List<Integer>> list = new ArrayList<List<Integer>>(); // final list 
    List<Integer> l = new ArrayList<Integer>(); // l is list 
    List<Integer> m = new ArrayList<Integer>(); // m is 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 to temp 
    list.add(temp); 
    System.out.println("temp: "+temp); 
    System.out.println("list: "+list); 


    temp.addAll(m); // add m to temp1 
    list.add(temp); 
    System.out.println("temp: "+temp); 
    System.out.println("list: "+list); 
} 

结果是列表,任何人都可以回答

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]] 

我觉得应该是:

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]] 

为什么上次名单[[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6]]

+1

哪里定义了temp1? –

回答

1

我将temp1重命名为temp以便正确编译。

这是因为当你第一次执行“list.add(temp);”

list获得对temp的引用。所以当temp的内容被改变时,list的内容也会被改变。

public static void main(String[] args) { 
    List<List<Integer>> list = new ArrayList<List<Integer>>(); // final list 
    List<Integer> l = new ArrayList<Integer>(); // l is list 
    List<Integer> m = new ArrayList<Integer>(); // m is 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 to temp1 
    list.add(temp); // list now references to temp. So when the content of temp is changed, the content of list also gets changed. 
    System.out.println("temp: "+temp); 
    System.out.println("list: "+list); 


    temp.addAll(m); // add m to temp. The content of temp is changed, so does the content of list 
    list.add(temp); 
    System.out.println("temp: "+temp); 
    System.out.println("list: "+list); 
} 
+0

感谢您的回答。 –

+0

不客气:) – Brian

1

list列表结束了两个引用相同的列表(temp)。通过创建第二个临时列表,将temp的内容添加到它,然后添加4,5和6,然后将该临时列表添加到list,可以实现所需的行为。

0

我假设代码中没有temp1变量,它与temp相同。 第一次在“list”中添加“temp”后,第一个元素的内容在更改temp时发生了变化,这让您感到惊讶。你缺少的是“列表”是参考文献的列表,因此它的第一个元素是参考到“temp”,而不是其内容的副本。因此,无论何时“temp”发生变化,即使“”list“的内容没有变化,也会在打印输出中报告。”

您可以通过添加一些内容来检查此行为,例如“temp”打印之前,不更改“列表”。你会看到100会出现在打印输出中。

+0

非常感谢,我知道“参考名单”的含义。 –

+0

@JZHOU欢迎您。但是,然后没有看到有什么问题。 :) –