【问题标题】:Java memory allocation in ArraylistArraylist 中的 Java 内存分配
【发布时间】:2013-08-30 14:21:23
【问题描述】:

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

发送

【问题讨论】:

  • 为什么不看源码!?
  • 这些是 JVM 本机调用。它没有在 Java 中实现。
  • ArrayList“未在 Java 中实现”是从什么时候开始的?

标签: java memory-management arraylist


【解决方案1】:

因此,当您在 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本地方法代码。

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2017-03-24
      • 2014-06-08
      • 2012-03-01
      • 1970-01-01
      • 2019-03-08
      • 2011-12-02
      • 2015-12-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多