【发布时间】:2018-06-15 21:53:07
【问题描述】:
在调试应用程序时,在无效索引处访问 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,而正在访问的 ArrayList 的 .size() 仍然是 3。这个后备数组的长度如何修改为5的长度?尤其是在源代码中,如果显示除.size() 之外的任何值,人们会认为它是10。
我希望修改内部支持数组以适应其中元素数量的长度,特别是为了抛出ArrayIndexOutOfBoundsException,因为当它与@不匹配时显示的长度会很混乱ArrayList 的 987654340@。
【问题讨论】:
标签: java android arrays arraylist