Is there a way to copy an array to the same array with fewer elements

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 using System.arraycopy (...), but the size of the array has not changed.

int[] array = {90,78,67,56,45,34,32,31};
System.arraycopy(array, 1, array, 0, array.length-1);

what i need is an array should consist of 78,67,56,45,34,32,31 elements with an array size of 7

there is a way to do this by copying it 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 that’s not how I want. I need this to be done without the help of another array.

+4
source share
3 answers

Java, Java , . , ArrayList .., .

, .

delete-item-from-array-and-shrink-array
how-do-i-remove-objects-from-an-array-in-java

, , ,

ArrayUtils.removeElement(Object [], Object) org.apache.commons.lang - .

, , , , . , !

+3

Java. , , .


FWIW: → < , ( ):

int[] arrayB = Arrays.copyOfRange(arrayA, 1, arrayA.length);

→ < < < System.arrayCopy. arraycopy javadoc :

" src dest , , srcPos srcPos + length - 1 length , destPos destPos + length - 1 ."

, .

+3

, Arraylist<> java

ArrayList arraylistobject = new ArrayList();

arraylistobject.remove(); arraylist.size(); , .

?

- static in size, . Array. ArrayList - dynamic in size. ArrayList , ArrayList. ArrayList, .

0

Source: https://habr.com/ru/post/1618666/


All Articles