How to removes an item from an array in java using a method?

74 Views Asked by At

I have to create a method that takes in an array and value as arguments and returns a new array with the specified value removed.

Here's my attempt:

public static int[] remove(int[] nums,int value){
    int[] after = new int[nums.length-1];
    for (int i = 0; i < nums.length; i++) {
        if (!(nums[i] == value)) {
            after[i] = nums[i];
        }
    }
    nums = after;
    return nums;
}

The code throws

ArrayIndexOutOfBoundsException

bur I don't know why.

3

There are 3 best solutions below

0
On

Code is trying to copy values from original array to new array leaving a blank or space(value 0) in place of targeted value. The error ArrayIndexOutOfBoundsException is showing because you are initialising the after with nums.lenth-1 int[] after = new int[nums.length-1]; You can change that or swap the targeted element with the last element and copy entire array except the last.

public static int[] remove (int[] nums,int value){
    int[] after = new int[nums.length-1];

    for(int i = 0; i < nums.length; i++) {
        if((nums[i] == value)) {
            //changing the target value with the last value of nums array
            nums[i]=nums[nums.length-1];
            nums[nums.length-1]=value;
        }
    }

    //Copying the entire array except the last
    for(int i=0;i<nums.length-1;i++){
        after[i]=nums[i];
    }
    return after;
}

And I am assuming that there is only one target element

0
On

KISS. It's a 1-liner:

public static int[] remove(int[] nums, int value){
    return IntStream.stream(nums).filter(i -> i != value).toArray();
}
0
On

First you need to find how big the new array is, after you can populate the new array without the value to remove. There are better ways to do this, but this is to get you started.

public static int[] remove (int[] nums, int value)
{
    int[] after;

    //find out the length of the array
    int count = 0;
    for (int num : nums)
    {
        if (num != value)
        {
            count++;
        }
    }

    after = new int[count];

    //add all the elements except the remove value
    int i = 0;
    for (int num : nums)
    {
        if(num != value)
        {
            after[i] = num;
            i++;
        }
    }

    return after;
}