Search code examples
javaarrayssub-array

The Java way to copy a subarray into an initialized array


outputArray[w:lastIndex] = array[v:lastIndex]

I want to copy a subarray into another sub array which has already been initialized.

Is there any inbuilt function which can check :

1) Number of elements to be copied are same. 2) That it is not causing an indexOutOfBoundException

On the RHS I can do something like :

Arrays.copyOfRange(array,v,lastIndex+1)

I don't know if anything can be done on the LHS.

I have to use an Integer Array + I know it defies the purpose of an array.


Solution

  • You can use System.arraycopy :

    System.arraycopy (sourceArray, sourceFirstIndex, outputArray, outputFirstIndex, numberOfElementsToCopy);
    

    It does, however, throw IndexOutOfBoundsException is you provide invalid parameters.

    If I understand the parameters in your example correctly, you need something like :

    System.arraycopy (array, v, outputArray, w, lastIndex - v);
    

    or

    System.arraycopy (array, v, outputArray, w, lastIndex - v + 1);
    

    if you want the element at lastIndex to be copied too.