Java在向ArrayList添加新元素时,如何处理获取新内存空间的问题?例如,在列表后面没有空闲空间的情况下。
/**
* Increases the capacity of this <tt>ArrayList</tt> instance, if
* necessary, to ensure that it can hold at least the number of elements
* specified by the minimum capacity argument.
*
* @param minCapacity the desired minimum capacity
*/
public void ensureCapacity(int minCapacity) {
modCount++;
int oldCapacity = elementData.length;
if (minCapacity > oldCapacity) {
Object oldData[] = elementData;
int newCapacity = (oldCapacity * 3)/2 + 1;
if (newCapacity < minCapacity)
newCapacity = minCapacity;
// minCapacity is usually close to size, so this is a win:
elementData = Arrays.copyOf(elementData, newCapacity);
}
}
Arrays.copyOf方法
进一步到达以下本地方法: public static native void arraycopy(Object src, int srcPos,
Object dest, int destPos,
int length);
对于Java,您需要查看openjdk
的本地方法代码。
Java的ArrayList通常会确保数组有足够的空间来存放元素。如果数组长度不够,则会为它们提供更多的空间:创建一个原始数组大小两倍的新数组,并将元素复制到其中。(DEFAULT_CAPACITY = 10)
public void ensureCapacity(int minCapacity){
int current = data.length;
if (minCapacity > current)
{
E[] newData = (E[]) new Object[Math.max(current * 2, minCapacity)];
System.arraycopy(data, 0, newData, 0, size);
data = newData;
}
}
你可以从ArrayList的实现中ensureCapacity方法看出来:
http://developer.classpath.org/doc/java/util/ArrayList-source.html
如果内存不足,它会抛出“java.lang.OutOfMemoryError: Java heap space”错误。你可以在这里检查:http://javarevisited.blogspot.com/2011/09/javalangoutofmemoryerror-permgen-space.html
ArrayList
在 Java 中何时变成了 "not implemented" 的? - Steve Kuo