Home » Core Java » Java Copy Array Example

About Mary Zheng

Mary Zheng
Mary has graduated from Mechanical Engineering department at ShangHai JiaoTong University. She also holds a Master degree in Computer Science from Webster University. During her studies she has been involved with a large number of projects ranging from programming and software engineering. She works as a senior Software Engineer in the telecommunications sector where she acts as a leader and works with others to design, implement, and monitor the software solution.

Java Copy Array Example

1. Introduction

Java array is an object which represents a data structure that contains elements of a similar data type. Array in java is index-based, the first element of the array is stored at the 0 index. Java has provided several ways to copy an array over time:

  • System.arraycopy – provided since version 1.0. It copies an array from a source array to a destination array. It starts the copy from the source position to the target position with the specified length.
  • Object.clone() – provided since version 1.0. It creates and returns a copy of the object. If the object is an array, then the array is cloned into a new array with the same content.
  • Arrays.copyOf – provided since version 1.6. It copies the specified array, truncating or padding with false (if necessary) so the copy has the specified length.
  • Arrays.copyOfRange – provided since version 1.6. It copies the specified range of the specified array into a new array.
  • Stream.toArray – provides since version 1.8. It returns an array containing the elements of this stream.

In this example, I will demonstrate how to use these methods to copy an Integer, String, and Object array and check if it is a shallow copy or deep copy when copying an Object array. I will also demonstrate how to use these methods to copy a two-dimensional (2D) Integer array.

2. Technologies used

The example code in this article was built and run using:

  • Java 1.8.101
  • Maven 3.3.9
  • Eclipse Oxygen
  • JUnit 4.12

3. Maven Project

3.1 Dependency

Add Junit to the pom.xml.

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>java-demo-copyarray</groupId>
	<artifactId>java-demo-copyarray</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<build>
		<sourceDirectory>src</sourceDirectory>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.8.0</version>
				<configuration>
					<release>11</release>
				</configuration>
			</plugin>
		</plugins>
	</build>
	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
		</dependency>
	</dependencies>
</project>

3.2 DemoObject

In this step, I will create a DemoObject class which has data members, getters, setters, and constructors.

DemoObject.java

package org.jcg.zheng;

public class DemoObject {

    private char charValue;
    private String name;
    private int number;

    public DemoObject(final char charValue, final int number, final String name) {
        super();
        this.charValue = charValue;
        this.name = name;
        this.number = number;
    }

    public DemoObject(DemoObject dObj) {
        if (dObj != null) {
            this.name = dObj.getName();
            this.charValue = dObj.getCharValue();
            this.number = dObj.getNumber();
        }
    }

    public char getCharValue() {
        return charValue;
    }

    public String getName() {
        return name;
    }

    public int getNumber() {
        return number;
    }

    @Override
    public String toString() {
        return "DataObject [number=" + number + ", charValue=" + charValue + ", name=" + name + "]";
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + charValue;
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        result = prime * result + number;
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        DemoObject other = (DemoObject) obj;
        if (charValue != other.charValue)
            return false;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        if (number != other.number)
            return false;
        return true;
    }

    public void setCharValue(char charValue) {
        this.charValue = charValue;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setNumber(int number) {
        this.number = number;
    }

}

4. JUnit Tests

In this step, I will create several Junit test classes to demonstrate array copy for an Integer, String, and Object array. The array copy for other primitive data types: boolean, char, byte, short, long, double, and float are similar to the int type provided in this example.

4.1 Test Base

In this step, I will create a TestBase class to hold the common test data and validation methods.

  • copyStartAtZeroIndex – set the copy to start at the 0 index of the source array.
  • sourceStringArray – an array with three String values: “Mary”, “Zheng”, and “Test”. It is used as a source array for the String type.
  • sourceIntegerArray – an Integer array with five values: 1, 2, 3, 4, 5.
  • source2DArray – a 2D Integer array.
  • maryObject – a DemoObject whose name value is “Mary”.
  • zhengObject – a DemoObject whose name value is “Zheng”.
  • sourceObjectArray – an array with maryObject, zhengObject, and null. It is used as a source object array.
  • validate_IntArray – validate clonedArray has a different object reference from sourceIntegerArray. Validate clonedArray has the same value for each element at the same index. Validate changing either clonedArray or sourceIntegerArray does not affect each other.
  • validate_StringArray – validate clonedArray has a different object reference from sourceStringArray. Validate clonedArray has the same value for each element at the same index. Validate changing either clonedArray or sourceStringArray does not affect each other.
  • validate_shallowCopy_ObjectArray – during shallow copy, the copied array’s elements hold the same object reference to the source array’s elements, so changing the array’s elements on either copy or source affects each other.
  • validate_deepCopy_ObjectArray – during deep copy, the copied array’s elements have a different object reference from the source array’s elements, so changing the copied element doesn’t affect the source’s element, and vice versa.

TestBase.java

package org.jcg.zheng;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

public class TestBase {

    protected int[] sourceIntegerArray = { 1, 2, 3, 4, 5 };
    protected String[] sourceStringArray = { "Mary", "Zheng", "Test" };

    protected int[][] source2DArray = { sourceIntegerArray, { 3, 4 } };
    protected DemoObject maryObject = new DemoObject('A', 1, "Mary");
    protected DemoObject zhengObject = new DemoObject('B', 2, "Zheng");
    protected DemoObject[] sourceObjectArray = { maryObject, zhengObject, null };
    protected DemoObject[] sourceObjectArrayContainsNull = { maryObject, null };

    protected int copyStartAtZeroIndex = 0;

    protected void validate_IntArray(int[] clonedArray) {
        // the copied object is a different reference
        assertFalse(System.identityHashCode(sourceIntegerArray)
                - System.identityHashCode(clonedArray) == 0);

        // for primitive data type, change the clonedArray element does not affect the source array
        clonedArray[0] = 99;

        assertEquals(99, clonedArray[0]);
        assertEquals(1, sourceIntegerArray[0]);

        sourceIntegerArray[1] = 99;
        assertEquals(2, clonedArray[1]);
    }

    protected void validate_StringArray(String[] clonedArray) {
        // the copied object is a different reference
        assertFalse(System.identityHashCode(sourceStringArray)
                - System.identityHashCode(clonedArray) == 0);

        // change the clonedArray element does not affect the source array
        clonedArray[0] = "Dummy";

        assertEquals("Dummy", clonedArray[0]);
        assertEquals("Mary", sourceStringArray[0]);

        sourceStringArray[1] = "ZhengUpdate";
        assertEquals("Zheng", clonedArray[1]);
    }

    protected void validate_shallowCopy_ObjectArray(DemoObject[] clonedArray) {
        // the copied object is a different reference
        assertFalse(System.identityHashCode(sourceObjectArray)
                - System.identityHashCode(clonedArray) == 0);

        // the copied object element is the same reference
        assertTrue(
                System.identityHashCode(maryObject) - System.identityHashCode(clonedArray[0]) == 0);
        assertTrue(System.identityHashCode(zhengObject)
                - System.identityHashCode(clonedArray[1]) == 0);

        assertEquals(maryObject, clonedArray[0]);
        assertEquals(zhengObject, clonedArray[1]);

        // for the copied object, change one will affect the other due to object reference is same
        clonedArray[1].setName("Changed");
        assertEquals("Changed", sourceObjectArray[1].getName());

        sourceObjectArray[1].setNumber(99);
        assertEquals(99, clonedArray[1].getNumber());

    }

    protected void validate_deepCopy_ObjectArray(DemoObject[] clonedArray) {
        // the copied object is a different reference
        assertFalse(System.identityHashCode(sourceObjectArray)
                - System.identityHashCode(clonedArray) == 0);

        assertEquals(3, clonedArray.length);

        // the object element reference is different
        assertFalse(
                System.identityHashCode(maryObject) - System.identityHashCode(clonedArray[0]) == 0);
        assertFalse(System.identityHashCode(zhengObject)
                - System.identityHashCode(clonedArray[1]) == 0);

        assertEquals(maryObject, clonedArray[0]);
        assertEquals(zhengObject, clonedArray[1]);

        // the object change will NOT affect the other because of deep copy
        clonedArray[1].setName("Changed");
        assertEquals("Zheng", sourceObjectArray[1].getName());

        sourceObjectArray[1].setNumber(99);
        assertEquals(2, clonedArray[1].getNumber());
    }

}

4.2 Object.clone

Java has provided Object.clone method since version 1.0. We can use it to clone an array because an array is an object too. Here is the method syntax:

Object clone() throws CloneNotSupportedException

In this step, I will create several test methods to copy an Integer, String, and Object array then validate copied data. It also validates that copying an object array is a shallow copy. I will also use it to copy a 2D int array.

  • copy_IntArray – creates a copy of an integer array and validates that the copied data is same as the source data.
  • copy_2d_IntArray – creates a copy of a 2D integer array.
  • copy_StringArray – creates a copy of a String array and validates that the copied data is same as the source data.
  • copy_objectArray – creates a copy of an object array and validates that the copied array’s element contains the same object reference.

Object_cloneTest.java

package org.jcg.zheng;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

// Since Java 1.0
public class Object_cloneTest extends TestBase {

    @Test
    public void copy_IntArray() {
        int[] clonedArray = sourceIntegerArray.clone();

        assertEquals(sourceIntegerArray.length, clonedArray.length);
        assertEquals(sourceIntegerArray[0], clonedArray[0]);
        assertEquals(sourceIntegerArray[1], clonedArray[1]);
        assertEquals(sourceIntegerArray[2], clonedArray[2]);

        validate_IntArray(clonedArray);
    }

    @Test
    public void copy_2D_IntArray() {
        int[][] clonedArray = source2DArray.clone();

        assertEquals(source2DArray.length, clonedArray.length);
        assertEquals(source2DArray[0][0], clonedArray[0][0]);
        assertEquals(source2DArray[0][1], clonedArray[0][1]);
        assertEquals(source2DArray[1][0], clonedArray[1][0]);
        assertEquals(source2DArray[1][1], clonedArray[1][1]);
    }

    @Test
    public void copy_StringArray() {
        String[] clonedArray = sourceStringArray.clone();

        assertEquals(sourceStringArray.length, clonedArray.length);
        assertEquals(sourceStringArray[0], clonedArray[0]);
        assertEquals(sourceStringArray[1], clonedArray[1]);

        validate_StringArray(clonedArray);
    }

    @Test
    public void copy_ObjectArray() {
        DemoObject[] clonedArray = sourceObjectArray.clone();

        assertEquals(sourceObjectArray.length, clonedArray.length);
        validate_shallowCopy_ObjectArray(clonedArray);
    }

}

4.3 System.arraycopy

Java has provided a static System.arraycopy since version 1.0. It provides an easy way to specify the total number of elements to copy and the source and destination array index positions. Here is the method syntax:

static void arraycopy(Object src,int srcPos,Object dest,int destPos,int length)

Parameters:

  • src – the source array.
  • srcPos – starting position in the source array.
  • dest – the destination array.
  • destPos – starting position in the destination data.
  • length – the number of array elements to be copied.

In this step, I will create several test methods to show the arraycopy usages for Integer, String, DemoObject, and 2D int arrays:

  • copy_IntArray – it copies an integer array with a specified index position.
  • copy_2d_IntArray – it creates a copy of a 2D integer array.
  • copy_StringArray – it copies a String array.
  • copy_ObjectArray – it copies an object array with a specified index position. It validates that the array copy is a shallow copy.
  • exception_when_destination_is_null – it throws NullPointerException when the destination is a null object.
  • exception_when_copy_length_exceed_destination – it throws ArrayIndexOutOfBoundsException when the destination size is smaller than the specified range.
  • exception_when_copy_length_exceed_source – it throws ArrayIndexOutOfBoundsException when the copy range exceeds the original array index boundary.

System_arraycopyTest.java

package org.jcg.zheng;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;

import org.junit.Test;

// Since Java 1.0
public class System_arraycopyTest extends TestBase {

    private int length = 3;

    @Test
    public void copy_IntArray() {
        int[] destination = new int[length];

        System.arraycopy(sourceIntegerArray, copyStartAtZeroIndex, destination, copyStartAtZeroIndex, length);

        assertEquals(length, destination.length);
        assertEquals(sourceIntegerArray[copyStartAtZeroIndex], destination[0]);
        assertEquals(sourceIntegerArray[copyStartAtZeroIndex + 1], destination[1]);
        assertEquals(sourceIntegerArray[copyStartAtZeroIndex + 2], destination[2]);

        validate_IntArray(destination);
    }

    @Test
    public void copy_2D_IntArray() {
        int[][] clonedArray = new int[source2DArray.length][];
        for (int i = 0; i < source2DArray.length; i++) {
            int[] aSource = source2DArray[i];
            clonedArray[i] = new int[source2DArray.length];
            System.arraycopy(aSource, 0, clonedArray[i], 0, source2DArray.length);
        }

        assertEquals(source2DArray.length, clonedArray.length);
        assertEquals(source2DArray[0][0], clonedArray[0][0]);
        assertEquals(source2DArray[0][1], clonedArray[0][1]);
        assertEquals(source2DArray[1][0], clonedArray[1][0]);
        assertEquals(source2DArray[1][1], clonedArray[1][1]);
    }

    @Test
    public void copy_StringArray() {
        String[] destination = new String[length];

        System.arraycopy(sourceStringArray, copyStartAtZeroIndex, destination, copyStartAtZeroIndex, length);

        assertEquals(sourceStringArray.length, destination.length);
        assertEquals(sourceStringArray[0], destination[0]);
        assertEquals(sourceStringArray[1], destination[1]);

        validate_StringArray(destination);
    }

    @Test
    public void copy_ObjectArray() {
        DemoObject[] destination = new DemoObject[length];

        System.arraycopy(sourceObjectArray, copyStartAtZeroIndex, destination, copyStartAtZeroIndex, length);

        assertEquals(length, destination.length);
        validate_shallowCopy_ObjectArray(destination);
    }

    @Test
    public void padding_null_when_destination_is_bigger_than_original() {
        DemoObject[] destination = new DemoObject[5];

        System.arraycopy(sourceObjectArray, copyStartAtZeroIndex, destination, copyStartAtZeroIndex,
                sourceObjectArray.length);

        assertNull(destination[sourceObjectArray.length]);
        assertNull(destination[sourceObjectArray.length + 1]);
    }

    @Test(expected = NullPointerException.class)
    public void exception_when_destination_is_null() {
        System.arraycopy(sourceObjectArray, copyStartAtZeroIndex, null, copyStartAtZeroIndex,
                sourceObjectArray.length);
    }

    @Test(expected = ArrayIndexOutOfBoundsException.class)
    public void exception_when_copy_lenght_exceed_destination() {
        DemoObject[] destination = new DemoObject[1];
        System.arraycopy(sourceObjectArray, copyStartAtZeroIndex, destination, copyStartAtZeroIndex,
                destination.length + 1);
    }

    @Test(expected = ArrayIndexOutOfBoundsException.class)
    public void exception_when_copy_length_exceed_source() {
        DemoObject[] destination = new DemoObject[5];
        System.arraycopy(sourceObjectArray, copyStartAtZeroIndex, destination, copyStartAtZeroIndex,
                sourceObjectArray.length + 1);
    }

}

4.4 Arrays.copyOf and Arrays.copyOfRange

Java Arrays class has provided copyOf and copyOfRange methods to copy an array since version 1.6. It uses System.arraycopy internally with the assumption that the length of the result might not be the same as the original. It provides a set of methods for the primitive data types as well as the general data type <T>. Here is the method signature for <T>:

static boolean[] copyOf(T[] original, int newLength)
static T[] copyOfRange(T[] original, int from, int to)

Parameters:

  • original – the array from which a range is to be copied
  • newLength – the length of the copy to be returned
  • from – the initial index of the range to be copied, inclusive
  • to – the final index of the range to be copied, exclusive

In this step, I will create several test methods:

  • copy_IntArray – creates a copy of an integer array and validates that the copied data is same as the source data.
  • copy_IntArray_big – creates a copy of an integer array with a larger size and validates that the copied data is the same as the source data.
  • copy_IntArray_small – creates a copy of an integer array with a smaller size and validates that the copied data is the same as the source data.
  • copy_objectArray – creates a copy of an object array and validates that the copied array’s elements contain the same object reference.

Array_copyOfTest.java

package org.jcg.zheng;

import static org.junit.Assert.assertEquals;

import java.util.Arrays;

import org.junit.Test;

// Since Java 1.6
public class Arrays_copyOfTest extends TestBase {

    @Test
    public void copy_IntArray() {
        int[] copyofArr = Arrays.copyOf(sourceIntegerArray, sourceIntegerArray.length);

        assertEquals(sourceIntegerArray.length, copyofArr.length);
        validate_IntArray(copyofArr);
    }

    @Test
    public void copy_IntArray_big() {
        int[] copyofArr = Arrays.copyOf(sourceIntegerArray, sourceIntegerArray.length + 1);

        assertEquals(sourceIntegerArray.length + 1, copyofArr.length);
        assertEquals(0, copyofArr[sourceIntegerArray.length]);
        validate_IntArray(copyofArr);
    }

    @Test
    public void copy_IntArray_small() {
        int[] copyofArr = Arrays.copyOf(sourceIntegerArray, sourceIntegerArray.length - 1);

        assertEquals(sourceIntegerArray.length - 1, copyofArr.length);

        validate_IntArray(copyofArr);
    }

    @Test
    public void copy_2D_IntArray() {
        int[][] clonedArray = source2DArray.clone();

        assertEquals(source2DArray.length, clonedArray.length);
        assertEquals(source2DArray[0][0], clonedArray[0][0]);
        assertEquals(source2DArray[0][1], clonedArray[0][1]);
        assertEquals(source2DArray[1][0], clonedArray[1][0]);
        assertEquals(source2DArray[1][1], clonedArray[1][1]);
    }

    @Test
    public void copy_StringArray() {
        String[] copyofArr = Arrays.copyOf(sourceStringArray, sourceStringArray.length - 1);

        assertEquals(sourceStringArray.length - 1, copyofArr.length);
        assertEquals(sourceStringArray[0], copyofArr[0]);
        assertEquals(sourceStringArray[1], copyofArr[1]);

        validate_StringArray(copyofArr);
    }

    @Test
    public void copy_ObjectArray() {
        DemoObject[] clonedArray = Arrays.copyOf(sourceObjectArray, sourceObjectArray.length);

        assertEquals(sourceObjectArray.length, clonedArray.length);
        validate_shallowCopy_ObjectArray(clonedArray);
    }
}

I will create a similar test class for copyOfRange:

  • copy_IntArray – it creates a copy of an integer array and validates that the copied data is the same as the source data.
  • copy_StringArray – it copies a String array.
  • copy_objectArray – it creates a copy of an object array and validates that the copied array’s elements contain the same object reference.

Array_copOfRangeTest.java

package org.jcg.zheng;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;

import java.util.Arrays;

import org.junit.Test;

// since Java 1.6
public class Arrays_copyOfRangeTest extends TestBase {

    @Test
    public void copy_IntArray() {
        int[] copyofArr = Arrays.copyOfRange(sourceIntegerArray, copyStartAtZeroIndex,
                sourceIntegerArray.length);

        assertEquals(sourceIntegerArray.length, copyofArr.length);
        assertEquals(sourceIntegerArray[0], copyofArr[0]);
        assertEquals(sourceIntegerArray[1], copyofArr[1]);
        validate_IntArray(copyofArr);
    }

    @Test
    public void copy_StringArray() {
        String[] copyofArr = Arrays.copyOfRange(sourceStringArray, copyStartAtZeroIndex,
                sourceStringArray.length - 1);

        assertEquals(sourceStringArray.length - 1, copyofArr.length);
        assertEquals(sourceStringArray[0], copyofArr[0]);
        assertEquals(sourceStringArray[1], copyofArr[1]);

        validate_StringArray(copyofArr);
    }

    @Test
    public void copy_ObjectArray() {
        DemoObject[] clonedArray = Arrays.copyOfRange(sourceObjectArray, copyStartAtZeroIndex,
                sourceIntegerArray.length - 1);

        assertEquals(sourceIntegerArray.length - 1, clonedArray.length);
        validate_shallowCopy_ObjectArray(clonedArray);
    }

    @Test
    public void padding_null_when_dest_is_larger_then_original() {
        DemoObject[] clonedArray = Arrays.copyOfRange(sourceObjectArray, copyStartAtZeroIndex,
                sourceObjectArray.length + 1);

        assertEquals(sourceObjectArray.length + 1, clonedArray.length);
        assertNull(clonedArray[sourceObjectArray.length]);
        validate_shallowCopy_ObjectArray(clonedArray);
    }
}

4.5 Stream.toArray

Java 8 provides a Stream class which has a toArray method to copy an array. It is a deep copy as the copied array has a different object reference from the source array’s element object. Here is the method syntax:

Object[] toArray()

In this step, I will create a test class to copy an array.

  • copy_IntArray – creates a copy of an integer array and validates that the copied data is the same as the source data.
  • copy_2d_IntArray_lambda – creates a copy of a 2D integer array with the lambda expression.
  • copy_2d_IntArray_methodReference – creates a copy of a 2D integer array with the method reference.
  • copy_StringArray – copies a String array.
  • copy_objectArray – creates a copy of an object array and validates that the copied array’s elements contain the different object reference.

Arrays_stream_toArrayTest.java

package org.jcg.zheng;

import static org.junit.Assert.assertEquals;

import java.util.Arrays;

import org.junit.Test;

// Since Java 1.8
public class Arrays_stream_toArrayTest extends TestBase {

    @Test
    public void copy_IntArray() {
        int[] copyofArr = Arrays.stream(sourceIntegerArray).toArray();

        assertEquals(sourceIntegerArray.length, copyofArr.length);
        assertEquals(1, sourceIntegerArray[0]);
        assertEquals(1, copyofArr[0]);

        validate_IntArray(copyofArr);
    }

    @Test
    public void copy_2D_IntArray_lambda() {
        int[][] clonedArray = Arrays.stream(source2DArray).map((int[] row) -> row.clone())
                .toArray((int length) -> new int[length][]);

        assertEquals(source2DArray.length, clonedArray.length);
        assertEquals(source2DArray[0][0], clonedArray[0][0]);
        assertEquals(source2DArray[0][1], clonedArray[0][1]);
        assertEquals(source2DArray[1][0], clonedArray[1][0]);
        assertEquals(source2DArray[1][1], clonedArray[1][1]);
    }

    @Test
    public void copy_2D_IntArray_methodReference() {
        int[][] clonedArray = Arrays.stream(source2DArray).map(int[]::clone).toArray(int[][]::new);

        assertEquals(source2DArray.length, clonedArray.length);
        assertEquals(source2DArray[0][0], clonedArray[0][0]);
        assertEquals(source2DArray[0][1], clonedArray[0][1]);
        assertEquals(source2DArray[1][0], clonedArray[1][0]);
        assertEquals(source2DArray[1][1], clonedArray[1][1]);
    }

    @Test
    public void copy_StringArray() {
        String[] copyofArr = Arrays.stream(sourceStringArray).toArray(String[]::new);

        assertEquals(sourceStringArray.length, copyofArr.length);
        assertEquals(sourceStringArray[0], copyofArr[0]);
        assertEquals(sourceStringArray[1], copyofArr[1]);

        validate_StringArray(copyofArr);
    }

    @Test
    public void copy_ObjectArray() {
        DemoObject[] clonedArray = Arrays.stream(sourceObjectArray).map(DemoObject::new)
                .toArray(DemoObject[]::new);

        validate_deepCopy_ObjectArray(clonedArray);
    }
}

5. Demo

I will execute the Junit tests and capture the results.

Java Copy Array - Junit output
Figure 1 Junit Results

6. Java Copy Array – Summary

In this example, we demonstrated how to copy an array with five methods: System.arraycopy, Object.clone, Arrays.copyOf, Arrays.copyOfRange, and Stream.toArray.

Stream.toArray is a deep copy when copying an object array. The other four methods are a “shallow copy” when copying an object array.

7. Download the Source Code

This example consists of a Maven project to copy an array.

Download
You can download the full source code of this example here: Java Copy Array Example
(+3 rating, 3 votes)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of