Java ArrayList在第n个位置添加元素

时间:2018-11-29 13:24:13

标签: java arraylist indexoutofboundsexception

我对ArrayList有疑问。在初始化arraylist时,默认大小为10。

将新元素添加到arraylist时,如果将arraylist的大小增加75%,则说在arraylist中添加第7个值时,它将扩展长度。

我有一个arraylist,并且在其中添加了3个值(例如10、20和30)。我正在尝试在第10个索引处添加下一个值,但会抛出IndexOutOfBoundsException

为什么不允许使用该索引值添加值?

4 个答案:

答案 0 :(得分:0)

默认的容量为10,而不是大小。新的ArrayList的大小为0。如果列表中只有3个元素,则无法在索引10处插入内容,因为该索引超出了列表的大小。

来自documentation

  

投掷:

     

IndexOutOfBoundsException-如果索引超出范围(索引<0 || index> size())

答案 1 :(得分:0)

当我们创建一个ArrayList时,内部数组的大小为10。 但是它们也是ArrayList中的一个元素,称为int size,其值为0,并且仅在将元素添加到arraylist中时递增。 当我们调用方法size()时,将使用相同的'size'属性。

现在,如果我们尝试在第10个索引处添加元素,并且'size'属性仍为3,则按如下所示进行检查

if (index > size || index < 0) throw new IndexOutOfBoundsException; 

因此您将获得例外。

enter image description here

答案 2 :(得分:0)

因为add方法通过调用List来展开ensureCapacityInternal,请参见此处

public boolean add(E e) {
    ensureCapacityInternal(size + 1);  // Increments modCount!!
    elementData[size++] = e;
    return true;
}

如果索引已经超出范围,则add(index, element)方法不会扩展List

  /**
 * Inserts the specified element at the specified position in this
 * list. Shifts the element currently at that position (if any) and
 * any subsequent elements to the right (adds one to their indices).
 *
 * @param index index at which the specified element is to be inserted
 * @param element element to be inserted
 * @throws IndexOutOfBoundsException {@inheritDoc}
 */
public void add(int index, E element) {
    rangeCheckForAdd(index);

    ensureCapacityInternal(size + 1);  // Increments modCount!!
    System.arraycopy(elementData, index, elementData, index + 1,
                     size - index);
    elementData[index] = element;
    size++;
}

这是默认行为。 Source

答案 3 :(得分:0)

使用默认值创建ArrayList对象时,ArrayList的大小,而不是10。 10 is the size of Array backingObject[] elementData的列表。如果您尚未添加任何元素,则列表中的Size仍为returns 0。因此,如果尝试将索引设置为大于大小的索引,则将引发异常。来自ArrayList#set()

的以下方法调用
private void rangeCheck(int index) {
    if (index >= size)
        throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
相关问题