在Arraylist中添加新元素时,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方法
进一步延伸到下面的native方法,
public static native void arraycopy(Object src, int srcPos,
Object dest, int destPos,
int length);
所以对于java你要看openjdk
native方法代码。
关于Arraylist中的Java内存分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18535219/