3

在 Arraylist 中添加新元素时,java 如何处理获取新的内存空间?例如,列表后没有可用空间。

发送

4

2 回答 2

2

因此,当您在 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 method进一步达到了以下原生方法,

 public static native void arraycopy(Object src,  int  srcPos,
                                        Object dest, int destPos,
                                        int length);

因此,对于 java,您必须查看openjdk本机方法代码。

于 2013-08-30T14:34:51.423 回答
1

基本上,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

于 2013-08-30T14:41:41.653 回答