Copying an array in java

In this post I show some ways to copy arrays of primitive data and objects to another array.

  • Copying a one-dimensional array of primitives: suppose you want to copy a one-dimensional array of integers named “a” in an array named “b”, the simple assignment

    doesn’t work.
    Consider the following code:

    which has as output:

    It is clear that “a” and “b” point to the same object because the changes are reflected on the other one, this code does not assign a copy of the object pointed by “a” to “b”, it copies the reference of the same object.
    The following code creates a copy of “a” and assigns it to “b” using the static method System.arraycopy:


    It is also possible to copy the object by copying every single element within a loop.
  • Copy of multidimensional array of primitives: you can’t use System.arraycopy with multidimensional arrays but you have to assign each elements within a loop:

    with output:

    In the case of a two-dimensional array, you can use System.arraycopy to assign an entire row inside a for loop:
  • Copy of an array of objects: the above steps are about arrays of primitive, but here I want to copy an array of objects, in this case objects of the Point class.
    A first attempt might be this:

    but as you can see from the output:

    doesn’t work because I don’t copy the element but the reference to the element at line 21.
    The correct code is:

    which has as output:

    To get a copy of the Point object I use a constructor with the object to be copied as argument (copy constructor).
    Sometimes it is also possible to use the clone method to copy an object but be careful because the clone method might not return a copy with no connection to the original, especially if the class contains members that are not primitive because they are copied by reference.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.