Copy an array from one array to another

Copy an array from one array to another

Postby SHilpy » Mon Feb 25, 2013 2:57 am

How do we copy an array from one array to another?
SHilpy
 
Posts: 6
Joined: Thu Jan 31, 2013 2:34 am

Re: Copy an array from one array to another

Postby Kishan » Mon Feb 25, 2013 4:07 am

You can copy array by iterating or readily available method System.arraycopy().

Syntax:
System.arraycopy(Object src, int srcPos, Object dest, int destPos, int length)


Example:

int from[] = {1,2,3,4,5};
int to[] = new int[5];

Code: Select all
System.arraycopy(from, 0, to, 0, 5);


Java API Description:
Copies an array from the specified source array, beginning at the specified position, to the specified position of the destination array. A subsequence of array components are copied from the source array referenced by src to the destination array referenced by dest. The number of components copied is equal to the length argument. The components at positions srcPos through srcPos+length-1 in the source array are copied into positions destPos through destPos+length-1, respectively, of the destination array.
If the src and dest arguments refer to the same array object, then the copying is performed as if the components at positions srcPos through srcPos+length-1 were first copied to a temporary array with length components and then the contents of the temporary array were copied into positions destPos through destPos+length-1 of the destination array.

If dest is null, then a NullPointerException is thrown.

If src is null, then a NullPointerException is thrown and the destination array is not modified.
Kishan
 
Posts: 191
Joined: Tue Jan 29, 2013 4:21 am


Return to Core Java

Who is online

Users browsing this forum: No registered users and 1 guest

cron