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

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

问题描述

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

  int长度= 2:
ArrayList的<整数[]> NUMS =新的ArrayList<整数[]>(大小);
整数[] = VALUE1 {1,2,3};
整数[] =数值2 {1,2};
nums.add(1,值1); // java.lang.IndexOutOfBoundsException
nums.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的索引越界的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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