Creating new array with contents from old array while keeping the old array static

Method 1

int[] newArr = new int[4];
System.arraycopy(array, 0, newArr, 0, 4);

The method takes five arguments:

  1. src: The source array.
  2. srcPosition: The position in the source from where you wish to begin copying.
  3. des: The destination array.
  4. desPosition: The position in the destination array to where the copy should start.
  5. length: The number of elements to be copied.

This method throws a NullPointerException if either of src or des are null. It also throws an ArrayStoreException in the following cases:

  • If the src is not an array.
  • If the des is not an array.
  • If src and des are arrays of different data types.

Method 2

Utilize

Arrays.copyOf(array,4) to copy the first 4 elements, truncating the rest.

of

Arrays.copyOfRange(array,1,5) to copy elements 1-4 if you need the middle of an array.


int[] newArray = Arrays.copyOf(array,4);

You could create the new array in the size you want (4 in this case), and then use System.arrayCopy to copy the contents from one array to another.

Tags:

Java

Arrays