Remove specific index from array in java

前端 未结 6 1322
情歌与酒
情歌与酒 2020-12-11 23:35

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?

<         


        
6条回答
  •  暖寄归人
    2020-12-12 00:24

    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().

提交回复
热议问题