Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove specific index from array in java

Can I remove a specific element from array by mentioning index value? For example can I remove the character d by giving index value 1?

char[] words = { 'c', 'd', 'f', 'h', 'j' };
like image 673
GES Vadamanappakkam Avatar asked Jun 21 '26 21:06

GES Vadamanappakkam


1 Answers

Assuming you do not want your array to contain null values, then you would have to make a method that does it. Something like this should suffice:

public char[] remove(int index, char[] arr) {
    char[] newArr = new char[arr.length - 1];
    if(index < 0 || index > arr.length) {
        return arr;
    }
    int j = 0;
    for(int i = 0; i < arr.length; i++) {
        if(i == index) {
            i++;
        }
        newArr[j++] = arr[i];
    }

    return newArr;
}

Then just replace the old array with the result of remove().

like image 52
Fjotten Avatar answered Jun 23 '26 09:06

Fjotten



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!