gpt4 book ai didi

java - ArrayList 的后备数组的长度与 ArrayList 的 .size() 不同

转载 作者:行者123 更新时间:2023-11-29 04:18:22 25 4
gpt4 key购买 nike

调试应用程序时,访问 ArrayList 时抛出以下错误在无效索引处:

java.lang.ArrayIndexOutOfBoundsException: length=5; index=-1
at java.util.ArrayList.get(ArrayList.java:439)

无效索引(-1)在意料之中,但出乎意料的是长度为 5。ArrayList被访问被验证为具有 .size()3 .

深入研究 ArrayList 的源代码, 可以找到以下内容:

/**                                            
* Default initial capacity.
*/
private static final int DEFAULT_CAPACITY = 10;

/**
* Shared empty array instance used for default sized empty instances. We
* distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when
* first element is added.
*/
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};

/**
* The array buffer into which the elements of the ArrayList are stored.
* The capacity of the ArrayList is the length of this array buffer. Any
* empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
* will be expanded to DEFAULT_CAPACITY when the first element is added.
*/
// Android-note: Also accessed from java.util.Collections
transient Object[] elementData; // non-private to simplify nested class access

/**
* Constructs an empty list with an initial capacity of ten.
*/
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}

似乎当 ArrayList实例化,并添加第一项,默认情况下支持数组的长度为10 .当上述原始错误显示长度为 10 时,这已通过实验验证(一次) .

但是,在大多数运行中,错误中显示的支持数组的长度为 5 , 而 .size()ArrayList被访问仍然是3 .如何将后备数组的长度修改为 5 的长度?特别是给定源代码,如果有任何值不是 .size() 的值被显示出来,人们会期望它是10 .

我希望修改内部后备数组以适应其中元素数量的长度,尤其是为了抛出 ArrayIndexOutOfBoundsException。 , 因为显示的长度与 .size() 不匹配时会很困惑的 ArrayList .

最佳答案

首先 - 这是正常的。 ArrayList 这样做是为了更快。如果底层数组与列表大小匹配,添加/删除操作会慢得多(每次都需要重新分配数组)。

要回答您的直接问题,有多种方法可以实例化 ArrayList - 特别是通过将现有的 Collection 传递给它,或通过提供 int初始容量。这两者都可以为您提供比默认值更小的底层数组。

// Source code of other `ArrayList` constructors below (trimmed for clarity to how `elementData` gets initialized)

public ArrayList(int initialCapacity) {
...
this.elementData = new Object[initialCapacity];
...
}

public ArrayList(Collection<? extends E> c) {
...
elementData = c.toArray();
...
}

关于java - ArrayList 的后备数组的长度与 ArrayList 的 .size() 不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50883115/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com