Java的ArrayList的IndexOutOfBoundsException异常,尽管给人的初始容量 [英] Java ArrayList IndexOutOfBoundsException despite giving an initial capacity

查看:349
本文介绍了Java的ArrayList的IndexOutOfBoundsException异常,尽管给人的初始容量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我这样做

ArrayList<Integer> arr = new ArrayList<Integer>(10);
arr.set(0, 1);

Java的给我

Java gives me

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
    at java.util.ArrayList.rangeCheck(Unknown Source)
    at java.util.ArrayList.set(Unknown Source)
    at HelloWorld.main(HelloWorld.java:13)

有一个简单的方法可以让我pre-保留ArrayList的大小,然后立即使用指标,就像数组?

Is there an easy way I can pre-reserve the size of ArrayList and then use the indices immediately, just like arrays?

推荐答案

下面是从的ArrayList 来源:

构造:

public ArrayList(int initialCapacity) 
{
     super();

     if (initialCapacity < 0)
          throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity);
     this.elementData = new Object[initialCapacity];
}

您名为设置(INT,E)

public E set(int index, E element) 
{
     rangeCheck(index);  
     E oldValue = elementData(index);
     elementData[index] = element;
     return oldValue;
}

设置通话 rangeCheck(INT)

private void rangeCheck(int index) 
{
    if (index >= size) {
         throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }
}

这可能是微妙的,但是当你调用构造函数,尽管初始化一个对象[] ,你没有初始化尺寸。因此,从 rangeCheck ,你得到的 IndexOutOfBoundsException异常,因为尺寸 0,而不是使用设置(INT,E),您可以使用添加(E五)(增加电子类型电子到列表的末尾,你的情况:添加(1 )),这不会发生。或者,如果它适合你,你可以在另一种答案建议初始化为0的所有元素。

It may be subtle, but when you called the constructor, despite initializing an Object[], you did not initialize size. Hence, from rangeCheck, you get the IndexOutOfBoundsException, since size is 0. Instead of using set(int, E), you can use add(E e) (adds e of type E to the end of the list, in your case: add(1)) and this won't occur. Or, if it suits you, you could initialize all elements to 0 as suggested in another answer.

这篇关于Java的ArrayList的IndexOutOfBoundsException异常,尽管给人的初始容量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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