如何使用方法从java中的数组中删除项?

时间:2018-02-10 00:33:06

标签: java arrays indexoutofboundsexception

我必须创建一个方法,该方法接受一个数组和值作为参数,并返回一个删除了指定值的新数组。

这是我的尝试:

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;
}

代码抛出

  

ArrayIndexOutOfBoundsException异常

bur我不知道为什么。

3 个答案:

答案 0 :(得分:1)

首先,您需要找到新数组的大小,然后填充新数组而不删除值。有更好的方法可以做到这一点,但这是为了让你开始。

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;
}

答案 1 :(得分:1)

KISS。这是一个单行:

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

答案 2 :(得分:0)

代码正在尝试将值从原始数组复制到新数组,留下空格或空格(值0)来代替目标值。错误ArrayIndexOutOfBoundsException正在显示,因为您正在使用nums.lenth-1 int[] after = new int[nums.length-1];初始化之后 您可以更改它或将目标元素与最后一个元素交换并复制除最后一个元素之外的整个数组。

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;
}

我假设只有一个目标元素