通过将下一个项目移动到其位置来删除数组中的项目

时间:2014-10-14 08:53:33

标签: java arrays vector

我遇到这种方法的问题。这个方法位于一个名为vectorOfDogs的文件中,正如它所说的那样,它假设通过传入其中的标记号删除特定的狗并将所有内容推到一起。在推动之后,它假设减小尺寸。此方法在下面的注释行中为我提供了arrayIndexOutOfBoundsException。任何帮助将不胜感激。

Dog[] theDogs = new theDogs[capacity]

public void deleteDog(int tgNm) {
    for (int i=0; i<size; i++) {
        if (theDogs[i].getTagNumber() == tgNm) {
            for (int j=i; j<size; j++) {
                theDogs[j] = theDogs[i+1]; //this line gives an exception
                i--;
            }
        }
    }
    System.out.println("the dog has been deleted");
}

3 个答案:

答案 0 :(得分:0)

你正在迭代在[0; size]范围内存储变量i中的值,而不是在你标记的行上递增i,所以如果i = size-1,你在上一次迭代中尝试访问theDogs [大小]。

答案 1 :(得分:0)

您的代码中有三个问题:

  • 你不应该在嵌套循环中修改i
  • 您应该在到达size-1后停止,因为您在index+1
  • 处获取了元素
  • 您应将最后一项设置为null

以下是解决此问题的方法:

if (theDogs[i].getTagNumber() == tgNm) {
    for (int j=i; j<size-1; j++) {
        theDogs[j] = theDogs[j+1];
    }
    theDogs[--size] = null;
    i--;
}

将最后一项设置为null可防止无效循环,以防您删除最后一只狗。

答案 2 :(得分:0)

试试这个:

public void deleteDog(int tgNm) {
   for (int i=0,int reduction=0; i<size-reduction; i++) {
      if (theDogs[i].getTagNumber() == tgNm) {
        reduction++;
        for (int j=i; j<size-reduction; j++) {
          theDogs[j] = theDogs[j+1]; //this line gives an exception
        }
      i--
    }
}
System.out.println("the dog has been deleted");
}