Search code examples
javaarraysresizeshrink

Delete some items from an array and shrink array in Java


I have an array like this:
double[] my_input_array = { 0, 1, 2, 3, 4, 5, 6, 7, 8 };
and some known positions which represent where to remove items from the array.
For example if positions are 3 and 7 I would like to get a my_output_array = { 0, 1, 2, 4, 5, 6, 8 };

So I would like to have a function like this:

public double[] getShinkedArray(double[] my_input_array, int... positions){
    /* SOME CODE */
    return my_output_array;
}

I noticed this question Delete item from array and shrink array but these answers remove only one element at time from an array.


Solution

  • You can't shrink an array, you need to create a new one with the new size. You could do something like:

    public double[] getShinkedArray(final double[] my_input_array, final int... positions) {
        double[] outputArray = new double[my_input_array.length - positions.length];
        for (int i = 0, j = 0; i < my_input_array.length; i++) {
            if (Arrays.binarySearch(positions, i) < 0) {
                outputArray[j++] = my_input_array[i];
            }
        }
        return outputArray;
    }