Reputation: 11
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"]
Upvotes: 1
Views: 720
Reputation: 11
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.
Upvotes: 0
Reputation: 11882
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]
Upvotes: 2