【问题标题】:Dropping the first or last index from an array without getting an "Out of Bounds" Error从数组中删除第一个或最后一个索引而不会出现“越界”错误
【发布时间】:2015-10-02 20:25:14
【问题描述】:

我被指派创建一个程序,我必须在其中一种方法中提示用户输入他们想要删除其值的索引。我的问题是,当我尝试删除索引 0 时,我在索引 -1 处得到一个 ArrayIndexOutOfBoundsException。因此,为了解决这个问题,我尝试了i <= currentSize + 1,它修复了索引 0 的问题,但是最后一个索引出现了越界错误,因为 currentSize 比它们的数组大小大一。任何帮助,将不胜感激。

//This method drops the value of a selected index in the array.
private static void Drop ()
{
     int m =0;
     System.out.println("Choose an index that you would like to drop the value of:");    
     if(input.hasNextInt())
     {
         m = input.nextInt();
         for(int pos = 0; pos < values.length; pos++)
         {
             if(pos == m)
             {
                 for(int i = pos+1; i<=currentSize+1; i++)
                 {
                     values[i-1]= values[i];
                     values[i]=0;
                 }
                 currentSize--;
                 break;
             }
             else if(pos == 0)
             {
                 System.out.println("ERROR: There is not an index at the specified location.");
             }  
         }
     }
     else
     {
         System.out.println("ERROR: Please input a integer value.");
     }
}

【问题讨论】:

  • 从列表或数组中删除元素时,通常会向后遍历列表。这是因为如果列表自动调整大小(如 ArrayList),您不会跳过元素。
  • currentSize 代表什么?我没有看到它在代码中的任何地方初始化。
  • 缩进代码会更好

标签: java arrays indexoutofboundsexception


【解决方案1】:

这是一种高效且紧凑的方法:

private static void drop(int[] arr, int index, int currentSize) {
    System.arraycopy(arr, index + 1, arr, index, currentSize - index - 1);
}

这有效地将数组元素向左移动, 从指定的索引 + 1 开始,直到 currentSize。 它适用于任何有效的索引, 例如,对于一个大小为 3 的数组, 它适用于索引 0、1、2。 它不检查边界, 所以在这个例子中,索引 -1 或 3 会抛出 ArrayIndexOutOfBoundsException

使用此功能, 您可以将代码简化为:

private static void mainInputLoop() {
    System.out.println("Choose an index that you would like to drop the value of:");
    if (input.hasNextInt()) {
        index = input.nextInt();
        drop(values, index, currentSize--);
    } else {
        System.out.println("ERROR: Please input a integer value.");
    }
}

【讨论】:

  • 好吧,我这样做了,如果我回去将另一个值添加到新的空白索引中,程序将覆盖空白点和之前删除的点之间的所有索引值。因此,例如,如果我将 4 个值添加到长度为 5 的值数组中,然后删除索引 1,那么当我再次添加一个值时,程序将首先覆盖索引 2。
  • 值应该添加到arr[currentSize],前提是数组有容量。
【解决方案2】:

您可以使用System.arrayCopy() 来简化您的代码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-23
    • 2018-03-15
    • 2016-08-26
    相关资源
    最近更新 更多