尽管提供了初始容量,但 Java ArrayList IndexOutOfBoundsException [英] Java ArrayList IndexOutOfBoundsException despite giving an initial capacity

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

问题描述

当我这样做

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

Java 给了我

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)

有没有一种简单的方法可以预先保留 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];
}

你调用了set(int, E):

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

Set 调用 rangeCheck(int):

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

这可能很微妙,但是当您调用构造函数时,尽管初始化了 Object[],但您并未初始化 size.因此,从 rangeCheck,你得到 IndexOutOfBoundsException,因为 size 是 0.而不是使用 set(int, E),您可以使用 add(E e)(将 E 类型的 e 添加到列表的末尾,在您的情况下:add(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天全站免登陆