WebDevGuy WebDevGuy - 4 months ago 13
Java Question

Java ArrayList - adding arrays

I am trying to implement a List in Java, I am new to the language so it is probably something I am overlooking but it is not behaving how I would expect it to. I have created a demo to show what I am trying to explain.

When I add arrays to the List using Test.add(array) the data appears in the list how I would expect it to, however if I later change the contents of an array that I previously added to the list then the value in the list is also changed.

Is there any way around this? I would like to add the contents of an array to the list without just adding the array to the list?

Thanks :)

Here is the demo code:

public static void main(String[] args) {
List<String[][]> Test = new ArrayList<>();

String[][] TestOne = new String[1][1];
String[][] TestTwo = new String[1][1];

TestOne[0][0] = "1";
TestTwo[0][0] = "2";

Test.add(TestOne);
Test.add(TestTwo);

System.out.println();

TestTwo[0][0] = "CHANGED";

System.out.println();
}

Answer

Just pass a copy of array to add() function like this :

Test.add(TestOne.clone());
Test.add(TestTwo.clone());