本文介绍了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的索引越界
发布评论