ArrayList的索引越界

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

为什么 java.lang.IndexOutOfBoundsException 在这个例子中提出,如果ArrayList的规模已经predefined?如何解决这个问题呢?

int长度= 2:ArrayList的<整数[]> NUMS =新的ArrayList<整数[]>(大小);整数[] = VALUE1 {1,2,3};整数[] =数值2 {1,2};nums.add(1,值1); // java.lang.IndexOutOfBoundsExceptionnums.add(0,值2);

解决方案

您不能在另一种是设置前加上一个项目在一个ArrayList。如果你想做到这一点,你必须对地方分配给项目空值0第一位。

如果你这样做将工作:

int长度= 2:ArrayList的<整数[]> NUMS =新的ArrayList<整数[]>(大小);整数[] = VALUE1 {1,2,3};整数[] =数值2 {1,2};nums.add(0,NULL);nums.add(1,值1);nums.set(0,值2);

编辑/替换插件由一套更换空对象

Why java.lang.IndexOutOfBoundsException is raised in this example, if the size of ArrayList has been predefined? How to solve this problem?

int size = 2: ArrayList<Integer[]> nums = new ArrayList<Integer[]>(size); Integer[] value1 = {1,2,3}; Integer[] value2 = {1,2}; nums.add(1,value1); // java.lang.IndexOutOfBoundsException nums.add(0,value2);

解决方案

You cannot put an item in an ArrayList before the other one is set. If you want to do it you'll have to assign null values to the item on place 0 first.

It will work if you do:

int size = 2: ArrayList<Integer[]> nums = new ArrayList<Integer[]>(size); Integer[] value1 = {1,2,3}; Integer[] value2 = {1,2}; nums.add(0, null); nums.add(1,value1); nums.set(0,value2);

edit/ Replaced add by set to replace the null object

更多推荐

ArrayList的索引越界

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

发布评论

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

>www.elefans.com

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