标签:int list 扩展 [] obj bsp oid element 源码
ArrayList是Array的扩展版,具有自动增长的特性,可以理解为动态数组.
其内部的实现关键是:用以存储任何对象的Object[] elementData, 并在增加元素的时候,检测目前数组的大小是否足以容纳新元素,不足则扩容-复制-添加,其扩容算法如下:
JDK1.6
1 // JDK6的扩容机制 2 public void ensureCapacity(int minCapacity) { 3 modCount++; 4 int oldCapacity = elementData.length; 5 if (minCapacity > oldCapacity) { 6 Object oldData[] = elementData; 7 int newCapacity = (oldCapacity * 3)/2 + 1; 8 if (newCapacity < minCapacity) 9 newCapacity = minCapacity; 10 // minCapacity is usually close to size, so this is a win: 11 elementData = Arrays.copyOf(elementData, newCapacity); 12 } 13 }
JDK1.7+
1 private void grow(int minCapacity) { 2 // overflow-conscious code 3 int oldCapacity = elementData.length; 4 int newCapacity = oldCapacity + (oldCapacity >> 1); 5 if (newCapacity - minCapacity < 0) 6 newCapacity = minCapacity; 7 if (newCapacity - MAX_ARRAY_SIZE > 0) 8 newCapacity = hugeCapacity(minCapacity); 9 // minCapacity is usually close to size, so this is a win: 10 elementData = Arrays.copyOf(elementData, newCapacity); 11 }
在查资料时,发现各个博客对于增长的速率书写于我查看源码的速率不对,便猜想可能跟JDK版本有关。
也说明,写软件的软件要以当前JDK的源码为准,所以说查源码还是很有用的。
标签:int list 扩展 [] obj bsp oid element 源码
原文地址:http://www.cnblogs.com/lfm1996/p/6852034.html