java – remove ALL elements from an array after index


I have the following Array:

String [] array={"Hola", "mundo", "de", "Stack", "Overflow"};

I would like to remove the elements of the array that are after an index , in this case 2 Result: {"Hola", "mundo"}

This means that it would pass from an array String[5] to String[2]

Is there a function of some class that does this?

Something like:

array = ArrayUtils.removeAllElementsAfter(array, 2);

I know that an alternative can be made with ArrayList

Alternative with ArrayList:

Pass Array to ArrayList :

ArrayList <String> arraylist = new ArrayList <String> (Arrays.asList(array));

Delete all elements that are from index (2) to the end

arraylist.subList(2, arraylist.size()).clear();

Pass the ArrayList back to Array :

String[] array2 = arraylist.toArray(new String[0]);


There is something easier and faster:

String[] array={"Hola", "mundo", "de", "Stack", "Overflow"};
String[] newarray = Arrays.copyOfRange(array, 0, 2);

If the array doesn't have n length {"Hola"} and you don't want it to be filled with null values:

String[] newarray = Arrays.copyOfRange(array, 0, (array.length < 2 ? array.length : 2));

De la documentación:

Copies the specified range of the specified array into a new array.The
initial index of the range (from) must lie between zeroand
original.length, inclusive. The value at original[from] is placed into
the initial element of the copy(unless from == original.length or from
== to).Values from subsequent elements in the original array are placed intosubsequent elements in the copy. The final index of the
range(to), which must be greater than or equal to from,may be greater
than original.length, in which case null is placed in all elements of
the copy whose index isgreater than or equal to original.length –
from. The lengthof the returned array will be to – from.

The resulting array is of exactly the same class as the original

Hago un intento de traducción. Si alguien ve algún fallo que lo edite, que mi inglés es ordinario.

Copia el rango especificado del array especificado en un nuevo array.
El índice inicial del rango (from) debe estar entre cero y
original.length, inclusive. El valor del original[from] se ubica en el
elemento inicial de copy (a no ser que from == original.length o from
== to). Valores de los elementos subsecuentes del array original se ubican en los elementos subsecuentes de copy. El índice final del
rango (to), que debe ser mayor que o igual a from, puede ser mayor que
original.length y en este caso en los elementos de copy con índice
mayor o igual a original.length – from se colocan valores null. La
longitud del array resultante será hasta – from.

El array resultante es de exactamente la misma clase que el original.

Y con mis palabras pero más corto:

Arrays.copyOfRange(original, from, to) devuelve una copia de los
elementos del array original en el rango from (inclusive) – to
(exclusive). El valor de to puede ser mayor que la longitud del array original. En este caso el array resultante se rellena con valores null para los índices superiores de la longitud del array original. El array resultante es del mismo tipo que el original.

Scroll to Top