Say I have an array of integers,
int[] array = new int[7];
for(int i = 0; i < 7; i++)
{
array[i] = i;
}
Now i want to get only the first four numbers in that array
, and turn put that into another array.
So I really want something like...
newArray = array[0-3].
I know that syntax is wrong, but I'm just giving the general idea of what I'm trying to do, is anything like that possible? Or do i have to create a loop and add it manually into the newArray
?
The array_unshift() function adds new elements to the array. The new array values will be inserted at the beginning of the array. You can insert one value or as many as you like. Numeric keys will start at 0 and increase by 1 every time a new element is added.
int[] newArray = Arrays.copyOf(array,4);
Method 1
int[] newArr = new int[4];
System.arraycopy(array, 0, newArr, 0, 4);
The method takes five arguments:
src
: The source array.srcPosition
: The position in the source from where you wish to begin
copying.des
: The destination array.desPosition
: The position in the destination array to where the copy
should start.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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With