posted @ 2013-03-21 09:39 ytl 閱讀(314) | 評論 (0) | 編輯 收藏
ArrayList
關于Java中的transient,volatile和strictfp關鍵字 http://www.iteye.com/topic/52957
(1), ArrayList底層使用Object數據實現, private transient Object[] elementData;且在使用不帶參數的方式實例化時,生成數組默認的長度是10。
(2), add方法實現
關于Java中的transient,volatile和strictfp關鍵字 http://www.iteye.com/topic/52957
(1), ArrayList底層使用Object數據實現, private transient Object[] elementData;且在使用不帶參數的方式實例化時,生成數組默認的長度是10。
(2), add方法實現
public boolean add(E e) {
//ensureCapacityInternal判斷添加新元素是否需要重新擴大數組的長度,需要則擴否則不
//ensureCapacityInternal判斷添加新元素是否需要重新擴大數組的長度,需要則擴否則不
ensureCapacityInternal(size + 1); // 此為JDK7調用的方法 JDK5里面使用的ensureCapacity方法
elementData[size++] = e; //把對象插入數組,同時把數組存儲的數據長度size加1
return true;
}
JDK 7中 ensureCapacityInternal實現
private void ensureCapacityInternal(int minCapacity) {
modCount++;修改次數
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);//如果需要擴大數組長度
}
/**
* The maximum size of array to allocate. --申請新數組最大長度
* Some VMs reserve some header words in an array.
* Attempts to allocate larger arrays may result in
* OutOfMemoryError: Requested array size exceeds VM limit --如果申請的數組占用的內心大于JVM的限制拋出異常
*/
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;//為什么減去8看注釋第2行
/**
* Increases the capacity to ensure that it can hold at least the
* number of elements specified by the minimum capacity argument.
*
* @param minCapacity the desired minimum capacity
*/
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1); //新申請的長度為old的3/2倍同時使用位移運算更高效,JDK5中: (oldCapacity *3)/2+1
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0) //你懂的
newCapacity = hugeCapacity(minCapacity);
// minCapacity is usually close to size, so this is a win:
elementData = Arrays.copyOf(elementData, newCapacity);
}
//可以申請的最大長度
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}
posted @ 2011-09-24 15:30 ytl| 編輯 收藏