简体   繁体   English

为什么此arraylist中的索引超出范围错误?

[英]Why the index out of bounds error in this arraylist?

Why does this code cause an index out of bounds error? 为什么此代码会导致索引超出范围错误?

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

The first size is 10 , but when you remove an element, it becomes 9, so when the index i gets to 9 you can't access the box 9 has it does not exists (as index starts at 0 ) 第一个大小为10 ,但是当您删除一个元素时,它的大小为9,因此当索引i达到9如果它不存在,则无法访问9框(因为索引从0开始)


You need to get the current size at each iteration as you're modifying it 修改时,您需要在每次迭代时获取当前大小

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]

Also the 4 is not deleted, why ? 另外4没有被删除,为什么?

  • Because when you check index 2 you find the value 3 so you remove it, 因为当您检查索引2会找到值3因此将其删除,
  • then all the values go down in the list, the value 4 is not at index 2 , 然后所有值都在列表中,值4不在索引2
  • as i will be now 3 you won't check that box 因为i现在是3您不会选中该框

To remove both 3 and 4 you can use one of the following solution: 要同时删除34 ,可以使用以下解决方案之一:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM