Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete an entry from an array in Java so that the other entries remain in order

Tags:

java

arrays

Forgive the clunky title

I want to write a method that removes a specific entry from an array, but doesn't leave a null gap in the array. For example if a String array contained

|aa,bb,cc,dd,ee|

the user would be prompted to enter which number they wanted removed, the method would find the index of that entry, remove that index, then move the null entry to the last slot.

So if the user entered cc, the array's contents would be

|aa,bb,dd,ee,null|

EDIT: I realized I left out some information here. the entry I'm looking to remove will be passed from another method. I will then use a for loop to find the index of the entry (If not found nothing is done). However I'm stuck on how to do the deletion.

like image 541
Bottlecaps Avatar asked Jan 17 '26 19:01

Bottlecaps


2 Answers

First of all: I strongly suggest to use an ArrayList where you can easily remove and add items without having to change the rest of the collection (it also has a toArray() method).

That being said, tihs would be a sample solution to do it with just arrays:

public static void main(String[] args) {
    String[] arr = new String[5];
    arr[0] = "aa";
    arr[1] = "bb";
    arr[2] = "cc";
    arr[3] = "dd";
    arr[4] = "ee";

    System.out.println(Arrays.toString(arr));

    int deleteIndex = 2;        
    System.arraycopy(arr, deleteIndex + 1, arr, deleteIndex, arr.length - deleteIndex - 1);
    arr[4] = null;

    System.out.println(Arrays.toString(arr));
}

Output:

[aa, bb, cc, dd, ee]
[aa, bb, dd, ee, null]

The idea is to to shift the elements one place ahead starting from the index to delete + 1. Afterwards you set the latest item manually to null or it will duplicate the last entry.

like image 123
Jeroen Vannevel Avatar answered Jan 20 '26 10:01

Jeroen Vannevel


I would do it like this maybe:

for (int i = index; i < array.length -1; i++) {
    array[i] = array[i+1];
}
array[array.length - 1] = null;
like image 34
Blub Avatar answered Jan 20 '26 10:01

Blub