如何将数组复制/添加到数组列表中



我是java新手,我一直在努力将String数组复制到ArrayList,但它不存储值,而是存储数组的地址。

String[] newLine = { "name", "location", "price" };
List<String[]> outList = new ArrayList<String[]>();
outList.add(newLine);
for(String[] rows: outList)
{
    System.out.println(row);
}

我得到打印

["名称"、"地点"、"价格"]

如果我更改newHeader的值,它在List中也会更改。

newLine[0] = "NEW VALUE";
for(String[] rows : outList)
{
    System.out.println(row);
}

输出:

["新价值"、"地点"、"价格"];

如何将数组的值添加/复制到ArrayList?

也许还不清楚,但我想在最后有这样的东西:

outList should contain *n* String Arrays e.g.      
["name", "location", "price"] 
["name2", "location2", "price2"]
["name3", "location3", "price3"]
["name4", "location4", "price4"]

您可以简单地执行以下操作:

list.addAll(Arrays.asList(myArray));

您可以通过存储数组的副本而不是数组本身来实现这一点:

String[] newLine = { "name", "location", "price" }
String[] copy = newLine.clone();
outList.add(copy);

clone()方法将创建一个具有相同元素和大小但引用/地址不同的数组副本。

如果现在更改原始数组的元素,则副本不会更改。

newLine[0] = "NEW VALUE";
System.out.println(Arrays.toString(newLine)); // prints [NEW VALUE, location, price]
System.out.println(Arrays.toString(copy)); // prints [name, location, price]

我已经发现我可以做到这一点:

String[] newLine = { "name", "location", "price" };
List<String[]> outList = new ArrayList<String[]>();
outList.add(new String []{newLine[0], newLine[1], newLine[2]});

现在,如果我要更改newLine的值,它将不会更改outList。但我不确定是否有更好的方法。

最新更新