Arrays.copyOfRange() vs System.arraycopy

Hi,

When to use below two functions. Are there special cases in which one is preferred to use over other?

Arrays.copyOfRange() and System.arraycopy


I was looking here

http://www.programcreek.com/2015/03/system-arraycopy-vs-arrays-copyof-in-java/ 

int[] copied = Arrays.copyOf(arr, 10); //10 the the length of the new array
System.out.println(Arrays.toString(copied));




copied = Arrays.copyOf(arr, 3); // are they truncating new array copied size from 10 to 3 in this step???
System.out.println(Arrays.toString(copied));
LVL 7
gudii9Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

dpearsonCommented:
System.arraycopy is used when you are copying between 2 arrays that already exist.  It takes a "source" and a "destination" array.

Arrays.copyOf is used when you want to create a copy of an existing array (possibly copying just a portion of the array).

So Arrays.copyOf() is much more commonly what you want - because you're trying to create a copy of an array.

Indeed if you look at the code for "copyOf" you can see that it calls System.arracopy internally.
It just allocates a new array and then copies to it.

    public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
        // Doug: This is fairly complicated code but all it is doing is allocating a new array
        T[] copy = ((Object)newType == (Object)Object[].class)
            ? (T[]) new Object[newLength]
            : (T[]) Array.newInstance(newType.getComponentType(), newLength);

        // Doug: Then here we copy from the original array to this newly allocated array
        System.arraycopy(original, 0, copy, 0,
                         Math.min(original.length, newLength));
        return copy;
    }

Open in new window


Hope that helps,

Doug
0
Kanti PrasadCommented:
Hi

With regards to your question

System.arraycopy  just copies

Arrays.copyOf()  -- can be used to copy as normal
                              -- also can create different sizes of an existing array.

In the initial statement  arr = {1,2,3,4,5} it is of size 5

but with the below code array arr changed to array size 10
int[] copied = Arrays.copyOf(arr, 10);  

Here it has changed to array size 3 -- so arr is downsized to 3
copied = Arrays.copyOf(arr, 3)   it made the copied array of size 3

Hence it is not truncation but the property of Arrays.copyOf() to  copy arrays but also to change arr sizes to bigger or smaller.

For your info there is  Array.copyOfRange()
Array.copyOfRange() is has the capability to to create an array of a different types, and a version where you can specify a range of elements to copy
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
gudii9Author Commented:
System.arraycopy() vs. Arrays.copyOf() in Java
 

If we want to copy an array, we can use either System.arraycopy() or Arrays.copyOf(). In this post, I use a simple example to demonstrate the difference between the two.


1. Simple Code Examples

System.arraycopy()

int[] arr = {1,2,3,4,5};
 
int[] copied = new int[10];
System.arraycopy(arr, 0, copied, 1, 5);//5 is the length to copy
 
System.out.println(Arrays.toString(copied));
Output:

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 1, 2, 3, 4, 5, 0, 0, 0, 0]
Arrays.copyOf()

int[] copied = Arrays.copyOf(arr, 10); //10 the the length of the new array
System.out.println(Arrays.toString(copied));
 
copied = Arrays.copyOf(arr, 3);
System.out.println(Arrays.toString(copied));
Output:

[1, 2, 3, 4, 5, 0, 0, 0, 0, 0]
[1, 2, 3]

i did not understand the difference of output w.r.t two above approaches clearly. please advise
0
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

Kanti PrasadCommented:
Hi

Ignore the 1st output of ten 0

Let us go through the 2nd output
[0, 1, 2, 3, 4, 5, 0, 0, 0, 0]

int[] copied = new int[10]; \\ Here copied array is defined with size 10

System.arraycopy(arr, 0, copied, 1, 5);//5 is the length to copy
\\ here arraycopy is telling arr to leave the 1st one then copy arr values which are 1,2,3,4,5 from the 2nd element till the 5th element. Hence in the output 1st is 0 2nd to 5th is 1,2,3,4,5 and as copied array is size 10 the rest are 0
 
this just printed after the above instructions
System.out.println(Arrays.toString(copied));

Here is the syntax in English
System.arraycopy(array that has data, starting position, destination array, Starting position of the element, Length);


int[] copied = Arrays.copyOf(arr, 10); //Here arr array size is increased from 5 to 10

System.out.println(Arrays.toString(copied));

So the output is 1,2,3,4,5 plus as you increased the size to 10 it printed 5 plus additional 5 0 as now the size of arr is 10 and this size 10 is copied in the copied array
[1, 2, 3, 4, 5, 0, 0, 0, 0, 0]


Here
copied = Arrays.copyOf(arr, 3); //Here arr array size is reduced  from 5 to 3
System.out.println(Arrays.toString(copied));

So the output is 1,2,3, only as you decreased the size to 3 so  it printed on 3 as it only copied into the copied array with size as 3
[1, 2, 3, ]
0
gudii9Author Commented:
Indeed if you look at the code for "copyOf" you can see that it calls System.arracopy internally.
It just allocates a new array and then copies to it.

How to see the code?
Please advise
0
gudii9Author Commented:
import java.util.Arrays;


public class ArrayCopyOfSystemArrayCopy {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int[] arr = {1,2,3,4,5};
		 
		int[] copied = new int[10];
		System.arraycopy(arr, 0, copied, 1, 5);//5 is the length to copy
		 
		System.out.println(Arrays.toString(copied));
		
		
		int[] copied2 = Arrays.copyOf(arr, 10); //10 the the length of the new array
		System.out.println(Arrays.toString(copied2));
		 
		copied = Arrays.copyOf(arr, 3);
		System.out.println(Arrays.toString(copied));
	}

}

Open in new window


above gave below output
[0, 1, 2, 3, 4, 5, 0, 0, 0, 0]
[1, 2, 3, 4, 5, 0, 0, 0, 0, 0]
[1, 2, 3]


when i pressed control and clicked
.copyOf

i got below source code which do have System.arraycopy


 public static int[] copyOf(int[] original, int newLength) {
        int[] copy = new int[newLength];
        [b]System.arraycopy[/b](original, 0, copy, 0,
                         Math.min(original.length, newLength));
        return copy;
    }

Open in new window


But i wonder why i do not see as below as you mentioned

    public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
        // Doug: This is fairly complicated code but all it is doing is allocating a new array
        T[] copy = ((Object)newType == (Object)Object[].class)
            ? (T[]) new Object[newLength]
            : (T[]) Array.newInstance(newType.getComponentType(), newLength);

        // Doug: Then here we copy from the original array to this newly allocated array
        System.arraycopy(original, 0, copy, 0,
                         Math.min(original.length, newLength));
        return copy;
    }

Open in new window


please advise
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.