Remove specific index from array in java

前端 未结 6 1317
情歌与酒
情歌与酒 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:17

    If you need to remove one or multiple elements from array without converting it to List nor creating additional array, you may do it in O(n) not dependent on count of items to remove.

    Here, a is initial array, int... r are distinct ordered indices (positions) of elements to remove:

    public int removeItems(Object[] a, int... r) {
        int shift = 0;                             
        for (int i = 0; i < a.length; i++) {       
            if (shift < r.length && i == r[shift])  // i-th item needs to be removed
                shift++;                            // increment `shift`
            else 
                a[i - shift] = a[i];                // move i-th item `shift` positions left
        }
        for (int i = a.length - shift; i < a.length; i++)
            a[i] = null;                            // replace remaining items by nulls
    
        return a.length - shift;                    // return new "length"
    }  
    

    Small testing:

    Character[] words = {'c','d','f','h','j'};
    removeItems(words, 1);
    System.out.println(Arrays.asList(words));       // [c, f, h, j, null]
    

提交回复
热议问题