【问题标题】:How to removes an item from an array in java using a method?如何使用方法从java中的数组中删除一个项目?
【发布时间】:2018-02-10 00:33:06
【问题描述】:

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

这是我的尝试:

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

我不知道为什么。

【问题讨论】:

  • 您的问题是什么?上面的代码不起作用吗?如果是这样,它是如何失败的?
  • 如果value 不是nums 数组中的最后一个元素,您将得到ArrayIndexOutOfBoundsException,因为after 长度比num 长度小1,而i 为高达nums.length - 1
  • 正如 KyrSt 所说,您需要添加错误消息,以便此问题对其他程序员有所帮助。运行时会发生什么?

标签: java arrays indexoutofboundsexception


【解决方案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;
}

【讨论】:

    【解决方案2】:

    KISS。这是一个 1-liner:

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

    【讨论】:

      【解决方案3】:

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

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

      我假设只有一个目标元素

      【讨论】:

        猜你喜欢
        • 2013-06-04
        • 2017-08-20
        • 2021-10-19
        • 1970-01-01
        • 2020-11-16
        • 1970-01-01
        • 1970-01-01
        • 2020-07-17
        • 2022-12-26
        相关资源
        最近更新 更多