0

I wonder if can I copy a 3-dimensional array, using ArrayList<>() as a middle step.

Please, consider the following code:

        /*variable declaration*/
        int[][][] array;
        int[][][] array2;
        ArrayList<int[][][]> list;
        ArrayList<int[][][]> list2;

        /*initialization*/
        array = new int[10][12][14];
        list = new ArrayList<>();

        list.add(array);

        //Construct 'list2', using all the elements contained in 'list'
        list2 = new ArrayList(list);

        array2 = list2.get(0);

I wonder if array2 is a complete copy (deep copy) of array, or is array2 a reference to array (points to same object in memory).

Also, is this an unsafe operation?

Soutzikevich
  • 991
  • 3
  • 13
  • 29
Esneyder
  • 471
  • 1
  • 5
  • 19
  • Unless I'm missing something, it would be a reference to the existing object. Try comparing via `==` – Vince Dec 10 '18 at 17:31
  • Just try, change value on one array, and print the other one, you'll see. This answer is no, an array is an object, you don"t make a copy here – azro Dec 10 '18 at 17:32
  • @tucuxi, If I ask is because I have tried and I have not de capacity to verify it... – Esneyder Dec 10 '18 at 17:36
  • you should have included the code that you used to try it; it helps in several ways: proves that you have tried, and allows feedback on how to test it better. I will be happy to reverse my downvote if you edit your question to include the test that did not work. – tucuxi Dec 11 '18 at 12:04

2 Answers2

3

Both val and val2 point to the same object in memory even after you've cloned the first list into the second.

You can prove this with:

System.out.println(val == val2);

prints "true"

That said, note that when you pass a collection to the ArrayList copy constructor all it does is simply construct a list containing the elements of the specified collection so I am not sure why you expected it to perform some type of "deep copying"

Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
0
ArrayList<int[][][]> vec2=new ArrayList(vec);

Here you are creating a new instance of ArrayList, but both vec and vec2 are referencing the same three-dimensional array.

You can look to this question. Here the Java 8 documentation for System.arraycopy

Kenna
  • 302
  • 4
  • 15