Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to copy an array to the same array with less number of elements [duplicate]

Tags:

java

arrays

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.

like image 846
Lahiru Jayathilake Avatar asked Jan 08 '23 01:01

Lahiru Jayathilake


2 Answers

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 and dest arguments refer to the same array object, then the copying is performed as if the components at positions srcPos through srcPos + length - 1 were first copied to a temporary array with length components and then the contents of the temporary array were copied into positions destPos through destPos + length - 1 of the destination array."

In other words, you don't need to do an explicit double copy.

like image 99
Stephen C Avatar answered Jan 30 '23 18:01

Stephen C


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 !!

like image 24
Sabir Khan Avatar answered Jan 30 '23 18:01

Sabir Khan