简体   繁体   中英

How to copy/add an Array to a List of Arrays

I'm new in the java, and I've been battling in copying a String array to an ArrayList but it does not store the values, instead stores the address of the array.

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

for(String[] rows: outList)
{
    System.out.println(row);
}

I get printed

["name", "location", "price"]

If i change the value of newHeader it changes as well in the List.

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

Output:

["NEW VALUE", "location", "price"];

How do I just add/copy the values of the Array to the ArrayList?

Maybe It isn't clear but I would like to have something like this at the end:

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));

You can achieve this by storing a copy of the array rather than the array itself:

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

The clone() method will create a copy of the array that has the same elements and size, but is a different reference / address.

If you now change an element of the original array, the copy doesn't change.

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]

I have figured out that I can do this:

String[] newLine = { "name", "location", "price" };

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

outList.add(new String []{newLine[0], newLine[1], newLine[2]});

Now if I will change the value of newLine it will not alter the outList. But I'm not sure if there is a better way to do this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM