The toArray
method in ArrayList
, Bloch uses both System.arraycopy
and Arrays.copyOf
to copy an array.
public <T> T[] toArray(T[] a) { if (a.length < size) // Make a new array of a's runtime type, but my contents: return (T[]) Arrays.copyOf(elementData, size, a.getClass()); System.arraycopy(elementData, 0, a, 0, size); if (a.length > size) a[size] = null; return a; }
How can I compare these two copy methods and when should I use which?
arraycopy() wins, for smaller than 10, manual for loop is better... Now I'm really confused. arraycopy() is a native call, which is most certainly faster.
arraycopy() simply copies values from the source array to the destination, Arrays. copyOf() also creates new array. If necessary, it will truncate or pad the content.
System. arraycopy does shallow copy, which means it copies Object references when applied to non primitive arrays. Therefore after System.
Using arraycopy() Method to Copy 2D Array in Java Likewise, we can copy 2D arrays using the arraycopy() method. We can copy elements of any 2D array without iterating all the array elements with this method.
The difference is that Arrays.copyOf
does not only copy elements, it also creates a new array. System.arraycopy
copies into an existing array.
Here is the source for Arrays.copyOf
, as you can see it uses System.arraycopy
internally to fill up the new array:
public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) { T[] copy = ((Object)newType == (Object)Object[].class) ? (T[]) new Object[newLength] : (T[]) Array.newInstance(newType.getComponentType(), newLength); System.arraycopy(original, 0, copy, 0, Math.min(original.length, newLength)); return copy; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With