ArrayList 索引越界 [英] ArrayList index out of bounds

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

问题描述

如果已经预定义了 ArrayList 的大小,为什么在此示例中会引发 java.lang.IndexOutOfBoundsException?如何解决这个问题呢?

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);

推荐答案

在设置另一项之前,您不能将一项放入 ArrayList.如果您想这样做,您必须首先为位置 0 上的项目分配空值.

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 by set 替换空对象

edit/ Replaced add by set to replace the null object

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

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