2013-01-05 143 views
1

我试图通过List<String[]>之间的函数,但我得到了一个奇怪的结果。Android返回错误ArrayList值

功能!

public List<String[]> tes(){ 

    List<String[]> test = new ArrayList<String[]>(); 

    String[] temp = {"a","b","c"}; 
    test.add(temp); 

    temp[0] = "d"; 
    temp[1] = "e"; 
    temp[2] = "f"; 

    test.add(temp); 

    return test; 
} 

提取。

String output = ""; 
    List<String[]> Results = db.tes(); 
    for (String[] row: Results) { 
     output = output + row[0] + " " + row[1] + "\n"; 
    } 

结果:

d e 
d e 

我真的不明白这一点。它应该是a b d e,但事实并非如此。

回答

0

您有一个物体温度。这意味着列表中的所有对象都有单独的临时链接。尝试对每个字符串使用new,结果将会不同。

祝你好运!

0

是的,这是因为,您已经将两个相同的对象(temp)添加到列表测试中。

列表(测试)两次保存同一对象的引用。

如果您在添加到列表后尝试更改对象的值,它也会在列表中获取更改,因为列表中包含对象的引用。

+0

谢谢,那是我寻找的答案。它超出了我的想法,但我不确定。谢谢! – user1950770

+0

欢迎您,如果对您有所帮助,请投票支持 –