Java Copy Array – Array Copy in Java

Filed Under: Java

Today we will look into different ways for java array copy. Java provides inbuilt methods to copy the array. Whether you want a full copy or partial copy of the array, you can do it easily using java inbuilt classes.

Java Copy Array

java copy array, array copy java
There are many ways to copy array in java. Let’s look at them one by one.

  1. Object.clone(): Object class provides clone() method and since array in java is also an Object, you can use this method to achieve full array copy. This method will not suit you if you want partial copy of the array.
  2. System.arraycopy(): System class arraycopy() is the best way to do partial copy of an array. It provides you an easy way to specify the total number of elements to copy and the source and destination array index positions. For example System.arraycopy(source, 3, destination, 2, 5) will copy 5 elements from source to destination, beginning from 3rd index of source to 2nd index of destination.
  3. Arrays.copyOf(): If you want to copy first few elements of an array or full copy of array, you can use this method. Obviously it’s not versatile like System.arraycopy() but it’s also not confusing and easy to use. This method internally use System arraycopy() method.
  4. Arrays.copyOfRange(): If you want few elements of an array to be copied, where starting index is not 0, you can use this method to copy partial array. Again this method is also using System arraycopy method itself.

So these are the four most useful methods for full and partial array copy. Note that all these inbuilt methods are to copy one-dimensional arrays only.

Java Copy Array Example

Now let’s see these java array copy methods in action with a simple java program.


package com.journaldev.util;

import java.util.Arrays;

public class JavaArrayCopyExample {

    /**
     * This class shows different methods for copy array in java
     * @param args
     */
    public static void main(String[] args) {
        int[] source = {1,2,3,4,5,6,7,8,9};
        int[] source1 = {1,2,3};
        int[] destination=null;
        System.out.println("Source array = "+Arrays.toString(source));
        
        destination = copyFirstFiveFieldsOfArrayUsingSystem(source);
        System.out.println("Copy First five elements of array if available. Result array = "+Arrays.toString(destination));
        
        destination = copyFirstFiveFieldsOfArrayUsingSystem(source1);
        System.out.println("Copy First five elements of array if available. Result array = "+Arrays.toString(destination));
        
        destination = copyFullArrayUsingSystem(source);
        System.out.println("Copy full array using System.copyarray() function. Result array = "+Arrays.toString(destination));
        
        destination = copyFullArrayUsingClone(source);
        System.out.println("Copy full array using clone() function. Result array = "+Arrays.toString(destination));
        
        destination = copyFullArrayUsingArrayCopyOf(source);
        System.out.println("Copy full array using Arrays.copyOf() function. Result array = "+Arrays.toString(destination));
        
        destination = copyLastThreeUsingArrayCopyOfRange(source);
        System.out.println("Copy last three elements using Arrays.copyOfRange() function. Result array = "+Arrays.toString(destination));
    }

    /**
     * This method copy full array using Arrays.copyOf() function
     * @param source
     * @return
     */
    private static int[] copyFullArrayUsingArrayCopyOf(int[] source) {
        return Arrays.copyOf(source, source.length);
    }
    
    /**
     * This method copy partial array (last 3 elements) using 
     * Arrays.copyOfRange() function
     * @param source
     * @return
     */
    private static int[] copyLastThreeUsingArrayCopyOfRange(int[] source) {
        //length check is necessary to avoid java.lang.ArrayIndexOutOfBoundsException
        //but for simplicity I am not doing that
        return Arrays.copyOfRange(source, source.length-3, source.length);
    }

    /**
     * This method copy full array using clone() function
     * @param source
     * @return
     */
    private static int[] copyFullArrayUsingClone(int[] source) {
        return source.clone();
    }

    /**
     * This method copy full array using System.arraycopy() function
     * @param source
     * @return
     */
    private static int[] copyFullArrayUsingSystem(int[] source) {
        int[] temp=new int[source.length];
        System.arraycopy(source, 0, temp, 0, source.length);
        return temp;
    }

    /**
     * This method copy full first five elements of array 
     * using System.arraycopy() function
     * @param source
     * @return
     */
    private static int[] copyFirstFiveFieldsOfArrayUsingSystem(int[] source) {
        if(source.length > 5){
            int[] temp=new int[5];
            System.arraycopy(source, 0, temp, 0, 5);
            return temp;
        }else{
            int[] temp=new int[source.length];
            System.arraycopy(source, 0, temp, 0, source.length);
            return temp;
        }
        
    }

}

Output of the above program is:


Source array = [1, 2, 3, 4, 5, 6, 7, 8, 9]
Copy First five elements of array if available. Result array = [1, 2, 3, 4, 5]
Copy First five elements of array if available. Result array = [1, 2, 3]
Copy full array using System.copyarray() function. Result array = [1, 2, 3, 4, 5, 6, 7, 8, 9]
Copy full array using clone() function. Result array = [1, 2, 3, 4, 5, 6, 7, 8, 9]
Copy full array using Arrays.copyOf() function. Result array = [1, 2, 3, 4, 5, 6, 7, 8, 9]
Copy last three elements using Arrays.copyOfRange() function. Result array = [7, 8, 9]

Java Array Copy – Shallow Copy

Note that all the inbuilt methods discussed above for array copy perform shallow copy, so they are good for primitive data types and immutable objects such as String. If you want to copy an array of mutable objects, you should do it by writing code for a deep copy yourself. Below is a program showing the problem with shallow copy methods.


import java.util.Arrays;

public class JavaArrayCopyMutableObjects {

	public static void main(String[] args) {
		Employee e = new Employee("Pankaj");
		
		Employee[] empArray1 = {e};
		
		Employee[] empArray2 = new Employee[empArray1.length];
				
		System.arraycopy(empArray1, 0, empArray2, 0, empArray1.length);
		
		System.out.println("empArray1 = "+Arrays.toString(empArray1));
		System.out.println("empArray2 = "+Arrays.toString(empArray2));
		
		//Let's change empArray1
		empArray1[0].setName("David");
		
		System.out.println("empArray1 = "+Arrays.toString(empArray1));
		System.out.println("empArray2 = "+Arrays.toString(empArray2));
		
	}

}

class Employee {
	private String name;

	public Employee(String n) {
		this.name = n;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	
	@Override
	public String toString() {
		return this.name;
	}
}

Now when we run the above program, below is the output produced.


empArray1 = [Pankaj]
empArray2 = [Pankaj]
empArray1 = [David]
empArray2 = [David]

As you can see that empArray2 got changed too even though it was never the intention. This can cause serious issues in your application, so you are better of writing your own code for deep copying of array. Similar case is there for java object clone method.

Below is the code for full array copy to use in this case. You can easily write something like this for partial array copy too.


import java.util.Arrays;

public class JavaArrayCopyMutableObjects {

	public static void main(String[] args) {
		Employee e = new Employee("Pankaj");
		
		Employee[] empArray1 = {e};
		
		Employee[] empArray2 = fullCopy(empArray1);
		
		System.out.println("empArray1 = "+Arrays.toString(empArray1));
		System.out.println("empArray2 = "+Arrays.toString(empArray2));
		
		//Let's change empArray1
		empArray1[0].setName("David");
		
		System.out.println("empArray1 = "+Arrays.toString(empArray1));
		System.out.println("empArray2 = "+Arrays.toString(empArray2));

		
	}

	private static Employee[] fullCopy(Employee[] source) {
		Employee[] destination = new Employee[source.length];
		
		for(int i=0; i< source.length; i++) {
			Employee e = source[i];
			Employee temp = new Employee(e.getName());
			destination[i] = temp;
		}
		return destination;
	}

}

class Employee {
	private String name;

	public Employee(String n) {
		this.name = n;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	
	@Override
	public String toString() {
		return this.name;
	}
}

Now when we run the above program, the output produced is:


empArray1 = [Pankaj]
empArray2 = [Pankaj]
empArray1 = [David]
empArray2 = [Pankaj]

As you can see, in deep copy our source and destination array elements are referring to different objects. So they are totally detached and if we change one of them, the other will remain unaffected.

That’s all for java copy array and how to properly do array copy in java programs.

Reference: System class arraycopy documentation

Comments

  1. CHOISUNGWON says:

    Thanks so much!

  2. Markus says:

    The examples demonstrate well the difference between a shallow copy and a deep copy for arrays of Objects. Thank you, Pankaj.

    However it depends on the desired behavior of your concrete application whether you need a shallow copy or a deep copy for ab array of Objects. In some cases the the behavior of the shallow copy is the desired one (or, in the concrete context, the “correct” one), whereas the deep copy may show the undesired or unexpected behavior.

    For example, think of your 2 arrays empArray1 and empArray2 as of two phone books (or similar directories) that refer to the same persons (the Employee instance). Each person exists only once in reality, regardless how many references there are to the person. So, changing the personal data of one employee refers to a change in the single, original entity – for example, if the person has married and therefore has changed the name – and it would be natural and desired to have this change reflected in any phone book, i.e., in both arrays.

  3. Krishan says:

    Thanks for sharing this. I think, as one can easily do all functionality (full or partial copy), it’s better to remember “System.arraycopy()”. only, rather than getting confused with other. 🙂

  4. torrent stream controller says:

    i believe it is Integer [] temp=new Integer[]. cause you cannot create an object of a primitive type

  5. jagdeep says:

    What is int1 in
    int[] temp=new int1;

  6. 51m1c says:

    Thank you soo much for posting this 😀

Leave a Reply

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

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages