ArrayList 越界异常 [英] ArrayList out of bounds exception

查看:30
本文介绍了ArrayList 越界异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

ArrayList<Integer> arr = new ArrayList<Integer>(10);
arr.set(0,5);

我收到一个索引越界错误,我不知道为什么.我已声明大小为 10 的 ArrayList.为什么会出现此错误?

I am getting an index out of bounds error, and I don't know why. I have declared the ArrayList of size 10. Why do I get this error?

推荐答案

您声明了一个 ArrayList,其初始容量为 10 个元素,但您没有向该列表添加元素,即该列表为空.set 将替换现有元素,但由于列表中没有元素,因此抛出异常.您必须在使用 add 方法之前添加元素.

You declared an ArrayList, that has the initial capacity of 10 elements, but you did not add an element to this list, i.e. the list is empty. set will replace an existing element, but since there is no element in the list, the exception is thrown. You have to add elements before, using the add method.

Initial capacity 表示列表内部维护的数组一开始大小为10.在向列表中添加更多元素时,此内部数组的大小可能会发生变化.

Initial capacity means that the array that the list maintains internally is of size 10 at the beginning. While adding more elements to the list, the size of this internal array might change.

这篇关于ArrayList 越界异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆