You cannot change the length of an array object after it is created. Here is an excerpt from JLS 10.2. Array Variables :
After creating an array object, its length never changes. To make an array variable a reference to an array of different lengths, a reference to another array must be assigned to the variable.
This means that for this task you will have to select a new array, which is one element smaller than the original, and copy the remaining elements.
If you need to delete an element with index k , and the original array has elements L , then you need to copy the elements (the upper bounds are exceptional):
- From
[0,k) to [0,k) ( k items) - From
[k+1,L) to [k,L-1) ( Lk-1 elements). - A total of
L-1 items copied
static String[] removeAt(int k, String[] arr) { final int L = arr.length; String[] ret = new String[L - 1]; System.arraycopy(arr, 0, ret, 0, k); System.arraycopy(arr, k + 1, ret, k, L - k - 1); return ret; } static void print(String[] arr) { System.out.println(Arrays.toString(arr)); } public static void main(String[] args) { String[] arr = { "a", "b", "c", "d", "e" }; print(arr);
Used by System.arraycopy ; You can always write your own if this is not permitted.
static void arraycopy(String[] src, int from, String[] dst, int to, int L) { for (int i = 0; i < L; i++) { dst[to + i] = src[from + i]; } }
This is a simplified implementation that does not handle src == dst , but in this case it is enough.
see also
Note for == for String comparisons
In most cases, using == to compare String objects is a mistake. Instead, you should use equals .
String ha1 = new String("ha"); String ha2 = new String("ha"); System.out.println(ha1 == ha2);
see also