Arraylist中的Java内存分配

标签 java memory-management arraylist

在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你要看openjdknative方法代码。

关于Arraylist中的Java内存分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18535219/

相关文章:

c# - 评论接口(interface)、实现还是两者兼而有之?

java - struts 2.0中Json解析webservice?

java - 将 ArrayList<?> 转换为 ArrayList<ClassName>

python - Python中的内存错误解决方案

memory-management - Chrome 分配配置文件 : why memory consumption for handleEvent is so huge?

java - 我如何通过ArrayAdapter用ArrayList填充Spinner?

java - ChromeDriver 的 org.openqa.selenium.remote.SessionNotFoundException

performance - 如何高效地 Navigator.push 内存 Flutter

java - 从数组列表添加元素到 List<List<String>>

java - 为什么ArrayList元素不能转换为int?