Monday, August 17, 2015

[Java] Difference between System.arraycopy() vs. Arrays.copyOf()


1. The Major Difference
Arrays.copyOf() will create a new array and return it and it use System.arraycopy() to copy elements
System.arraycopy() just copy elements

2. Example:



System.arraycopy()
int[] arr = {1,2,3,4,7};
 
int[] copy = new int[10];
System.arraycopy(arr, 0, copy, 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, 7, 0, 0, 0, 0]
Arrays.copyOf()
int[] arr = {1,2,3,4,7};
int[] copy = Arrays.copyOf(arr, 10); //10 the the length of the new array
System.out.println(Arrays.toString(copy));
copy = Arrays.copyOf(arr, 3);
System.out.println(Arrays.toString(copy));
Output
[1, 2, 3, 4, 7, 0, 0, 0, 0, 0]
[1, 2, 3]
References:
http://www.programcreek.com/2015/03/system-arraycopy-vs-arrays-copyof-in-java/

No comments:

Post a Comment