Monday, October 6, 2008

Array Copy

Arrays are an important way to save data. Sometimes we have to create a copy of that array to another.

We could acomplish this task with the following code:
public class Copy(){
  int[] array = new int[55555];
}

public int[] copyArray(){
  int[] arrayCopy = new int[array.length]
  for( int i = 0; i < array.length; i++ )
    arrayCopy[i] = array[i];
  return arrayCopy;
  }
For each position we copy the value from one array to another, that great but there's a better and easy way;


If we see the System class in API documentation there's a method called "arraycopy".

The actual code of the method is:
 public static native void arraycopy(Object src,  int  srcPos,
    Object dest, int destPos,int length);
The method is native, so the copy will be made by copy a segment of the memory and not for every position making it faster.

This provide us the ability to copy any segment of the original array, so the destination array doesn't need to have the same size as the original, maybe larger to expand the array or shorter to copy a fragment.
Also we can copy data from the same array
 System.arraycopy(array, 5, array, 0, array.length-5);
Copy the array since the 5 position.

1 comments:

Gus said...

:O That's really Interesting, the next time I need to copy an Array I'll use that function, I didn't know that it runs native making the copy faster =D