I have an array with 8 elements, and I need to remove the first element from it and copy it to the same array. I tried it using System.arraycopy(...) but the size of the array did not change.
int[] array = {90,78,67,56,45,34,32,31};
System.arraycopy(array, 1, array, 0, array.length-1);
what I need is, the array should consist 78,67,56,45,34,32,31 elements with the array size of 7
there is a way to do this by copying this to another array and assigning it to the first array
int arrayB = new int[array.length-1];
System.arraycopy(array, 1, arrayB, 0, array.length-1);
array = arrayB;
but this is not the way I want. I need it to be done without the help of another array.
You cannot change the size of an array in Java. Therefore, what you are trying to do is impossible.
FWIW: the most concise way to copy to a >>new<< array reducing its size by one (as per your example) is:
int[] arrayB = Arrays.copyOfRange(arrayA, 1, arrayA.length);
And you can copy elements >>within<< an array using a loop, or using System.arrayCopy
. The arraycopy
javadoc says:
"If the
src
anddest
arguments refer to the same array object, then the copying is performed as if the components at positionssrcPos
throughsrcPos + length - 1
were first copied to a temporary array withlength
components and then the contents of the temporary array were copied into positionsdestPos
throughdestPos + length - 1
of the destination array."
In other words, you don't need to do an explicit double copy.
Deleting an element from Java array and then shrinking array size is not a possibility in Java as arrays are of fixed length. Folks use different data structures like ArrayList etc whenever requirement is as such.
Lots of options have been put in here but none are one line answers that you are looking for.
delete-item-from-array-and-shrink-array
how-do-i-remove-objects-from-an-array-in-java
Of the options presented in above questions, I personally like the answer ,
Using ArrayUtils.removeElement(Object[],Object) from org.apache.commons.lang is by far the easiest way to do this.
Even in this case, the trick is to create a new array of new size and assign to same reference so original array is gone but yes, your application code is not required to create two arrays. Hope it helps !!
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