How do I remove objects from an array in Java?

前端 未结 20 1377
Happy的楠姐
Happy的楠姐 2020-11-22 01:20

Given an array of n Objects, let\'s say it is an array of strings, and it has the following values:

foo[0] = \"a\";
foo[1]          


        
20条回答
  •  天涯浪人
    2020-11-22 01:46

    If you need to remove 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:

    String[] a = {"0", "1", "2", "3", "4"};
    removeItems(a, 0, 3, 4);                     // remove 0-th, 3-rd and 4-th items
    System.out.println(Arrays.asList(a));        // [1, 2, null, null, null]
    

    In your task, you can first scan array to collect positions of "a", then call removeItems().

提交回复
热议问题