ArrayList 越界异常

编程入门 行业动态 更新时间:2024-10-28 14:31:36
本文介绍了ArrayList 越界异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我有以下代码:

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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-16 10:32:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/884884.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:异常   ArrayList

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!