【问题标题】:Why the index out of bounds error in this arraylist?为什么这个数组列表中的索引越界错误?
【发布时间】:2018-12-19 01:07:36
【问题描述】:

为什么这段代码会导致索引越界错误?

ArrayList<Integer> list2 = new ArrayList<Integer>();

for (int i = 1; i <= 10; i++){
    list2.add(i); //adding numbers to arraylist.  Length is equal to 10
}
int size = list2.size(); //size now equals 10

for (int i = 0; i < size; i++)
    if (list2.get(i) == 3 || list2.get(i) == 4)
    list2.remove(i);
System.out.println(list2);

【问题讨论】:

  • 您从数组列表中删除项目,但从不更新size 变量。所以在第一个remove之后,size就太大了。

标签: java arraylist indexing


【解决方案1】:

第一个大小是10,但是当你删除一个元素时,它变成了9,所以当索引i到达9你不能访问框9它不存在(因为索引开始于0)


您需要在每次修改时获取当前大小

for (int i = 0; i < list2.size(); i++) {
    if (list2.get(i) == 3 || list2.get(i) == 4) {
        list2.remove(i);
    }
}
//[1, 2, 4, 5, 6, 7, 8, 9, 10]

4 也没有被删除,为什么?

  • 因为当您检查索引 2 时,您会找到值 3,因此您将其删除,
  • 那么所有的值都在列表中,值4不在索引2,
  • 因为i 现在将变为3,所以您不会选中该框

要同时删除3 和4,您可以使用以下解决方案之一:

  • list2.removeIf(i -&gt; i == 3 || i == 4);
  • list2 = list2.stream() .filter(i -> i != 3 && i != 4) .collect(Collectors.toCollection(ArrayList::new));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-06
    • 1970-01-01
    • 2018-04-02
    • 2017-07-26
    • 2021-11-09
    • 1970-01-01
    • 2016-06-04
    • 2012-06-10
    相关资源
    最近更新 更多