android返回错误的ArrayList值
我试图在函数之间传递一个android返回错误的ArrayList值,android,arraylist,return-value,Android,Arraylist,Return Value,我试图在函数之间传递一个列表,但得到了一个奇怪的结果 功能 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";
列表
,但得到了一个奇怪的结果
功能
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;
}
我真的不明白。它应该是a b d e,但不是。您有一个对象温度。这意味着列表中的所有对象都有链接。尝试对每个字符串使用
new
,结果将不同
祝你好运 是的,因为,您已经将相同的对象(temp)添加到列表测试中两次 列出(测试)保存同一对象的引用两次
如果您在添加到列表后尝试更改对象的值,它也会在列表中得到更改,因为列表包含对象的引用。谢谢,这就是我要寻找的答案。我突然想到了,但我不确定。谢谢!
String output = "";
List<String[]> Results = db.tes();
for (String[] row: Results) {
output = output + row[0] + " " + row[1] + "\n";
}
d e
d e