Java的ArrayList中的ensureCapacity不工作 [英] java arraylist ensureCapacity not working
问题描述
无论我在做这个错误的或者说我不理解这种方法是如何工作的。
Either I'm doing this wrong or i'm not understanding how this method works.
ArrayList<String> a = new ArrayList<String>();
a.ensureCapacity(200);
a.add(190,"test");
System.out.println(a.get(190).toString());
我本来以为的ensureCapacity会让我插入一条记录与指数上升到该值。是否有不同的方式来做到这一点?
I would have thought that ensureCapacity would let me insert a record with an index up to that value. Is there a different way to do this?
我得到第三行的IndexOutOfBounds错误。
I get an IndexOutOfBounds error on the third line.
推荐答案
没有,的ensureCapacity
不会改变的逻辑大小的的的ArrayList
- 它改变了的容量的,这是清单可以达到前下一个需要复制值的大小
No, ensureCapacity
doesn't change the logical size of an ArrayList
- it changes the capacity, which is the size the list can reach before it next needs to copy values.
您必须非常清楚一个逻辑大小之间的差异(范围,即所有的值 [0,大小)
是可访问的,并增加了新的元素将索引添加尺寸
),并且更多的是一种实现细节的真正的能力 - 这是用于存储文件的支持数组的大小
You need to be very aware of the difference between a logical size (i.e. all the values in the range [0, size)
are accessible, and adding a new element will add it at index size
) and the capacity which is more of an implementation detail really - it's the size of the backing array used for storage.
调用的ensureCapacity
只能永远做在性能方面的差异(以避免过度复制) - 这并不影响什么是在列表中的逻辑模型,如果你明白我的意思。
Calling ensureCapacity
should only ever make any difference in terms of performance (by avoiding excessive copying) - it doesn't affect the logical model of what's in the list, if you see what I mean.
编辑:这听起来像你想有一个排序 ensureSize()
的方法,这可能会是这个样子:
It sounds like you want a sort of ensureSize()
method, which might look something like this:
public static void ensureSize(ArrayList<?> list, int size) {
// Prevent excessive copying while we're adding
list.ensureCapacity(size);
while (list.size() < size) {
list.add(null);
}
}
这篇关于Java的ArrayList中的ensureCapacity不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!