本文介绍了从列表中删除项目后,Java ArrayList引发IndexOutOfBoundsException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我们创建一个ArrayList并检查其大小时,其值将为0.但是,当我们添加一个元素并删除该元素,然后检查其大小时,它将引发异常.
When we create an ArrayList and check its size, it gives the value as 0. However, when we add an element and remove that element, and then check its size, it throws exception.
remove()方法的内部实现是什么,它可以更改空列表的定义?
What is the internal implementation in remove() method, that it changes the definition of an empty list?
下面的代码将输出设置为0.
Code below gives output as 0.
List<Integer> list2 = new ArrayList<Integer>(); System.out.println(list2.size());下面的代码引发异常:
List<Integer> list1 = new ArrayList<Integer>(); list1.add(1); System.out.println(list1.size()); list1.remove(1); System.out.println(list1.size()); 推荐答案list1.remove(1)
list1.remove(1)
您正在尝试从索引1中删除一个元素,而不是值1.因此,数组索引超出范围错误.
You are trying to remove an element from index 1, not the value 1. hence the array index out of bounds error.
更多推荐
从列表中删除项目后,Java ArrayList引发IndexOutOfBoundsException
发布评论