3
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.

Barend
  • 17,296
  • 2
  • 61
  • 80
technazi
  • 888
  • 4
  • 21
  • 42

4 Answers4

4

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.

Eran
  • 387,369
  • 54
  • 702
  • 768
2

You can use System#arraycopy, which takes arguments for the start indexes in both the source and destination arrays:

System.arraycopy(array, v, outputArray, w, lastIndex - v)
Mureinik
  • 297,002
  • 52
  • 306
  • 350
1

Maybe you can use fill function.

Javier Toja
  • 1,630
  • 1
  • 14
  • 31
0

you can use ArrayUtils library's addAll method

From document https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/ArrayUtils.html

Adds all the elements of the given arrays into a new array.

The new array contains all of the element of array1 followed by all of the elements array2. When an array is returned, it is always a new array.

 ArrayUtils.addAll(null, null)     = null
 ArrayUtils.addAll(array1, null)   = cloned copy of array1
 ArrayUtils.addAll(null, array2)   = cloned copy of array2
 ArrayUtils.addAll([], [])         = []
 ArrayUtils.addAll([null], [null]) = [null, null]
 ArrayUtils.addAll(["a", "b", "c"], ["1", "2", "3"]) = ["a", "b", "c", "1", "2", "3"]

Parameters:
array1 - the first array whose elements are added to the new array, may be null
array2 - the second array whose elements are added to the new array, may be null
Returns:
The new array, null if both arrays are null. The type of the new array is the type of the first array, unless the first array is null, in which case the type is the same as the second array.
Throws:
IllegalArgumentException - if the array types are incompatible

  [1]: https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/ArrayUtils.html
abhirathore2006
  • 3,317
  • 1
  • 25
  • 29