ArrayList的出界异常 [英] ArrayList out of bounds exception

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

问题描述

我有以下的code:

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

我得到一个索引出界失误,我不知道为什么。我宣布了的ArrayList 尺寸10.为什么我会收到这个错误?

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个元素的初始容量,但你没有添加元素添加到此列表,即该列表是空的。 设置将取代现有的元素,但由于没有在列表中没有的元素,则抛出异常。
你必须之前添加元素,使用添加方法。

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.

初始容量表示,列表内部维护数组的大小为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天全站免登陆