WebDevGuy WebDevGuy - 6 months ago 46
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";



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



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