當我們初始化一個ArrayList
時,Array List的大小最初爲0。這就是爲什麼代碼
for(int i=0;i<numo.size() ;i++) {
numo.add(i);
}
與numo.size()
打印什麼遍歷時,
數組列表JAVA
1.什麼是一個ArrayList?
數組列表是其中包含數組緩衝區的數組,其中存儲了ArrayList的元素。ArrayList的容量是此數組緩衝區的長度。
2.當我不提供數組列表intializtion過程中的任何大小會發生什麼?
加入第一元件時,在任何空的ArrayList將擴大到DEFAULT_CAPACITY
。
DEFAULT_CAPACITY value of an array list is 10
3.在接下來的初始化過程中會發生什麼?
ArrayList<Integer> numo = new ArrayList<Integer>();
這將調用數組列表構造函數會像
private static final Object[] EMPTY_ELEMENTDATA = {};
/**
* This would construct an empty list with an initial capacity of ten.
*/
public ArrayList() {
super();
this.elementData = EMPTY_ELEMENTDATA;
}
3.How我的值插入到數組列表?
I]此檢查內部陣列的容量,並將該元件到其內的數組緩衝區。
/*
Appends the specified element to the end of this list
e - element to be appended to this list
returns - true if element is added successfully - false otherwise
*/
public boolean add(E e) {
ensureCapacityInternal(size + 1); //Increments modCount!!
elementData[size++] = e;
return true;
}
4。數組容量(這裏的數組是指數組列表中的對象數組)在內部如何增加?
I] Ensuriy容量
private void ensureCapacityInternal(int minCapacity) {
if (elementData == EMPTY_ELEMENTDATA) {
minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
}
ensureExplicitCapacity(minCapacity);
}
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
II]如果陣列的容量是不夠的,保存新的元素 - 然後將數組的大小生長。
/**
* 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);
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);
}
5.我的ArrayList溢出嗎?
是
6.當沒有一個ArrayList拋出OutOfMemoryError()
?
當請求的陣列大小超過限制VM
7.什麼是一個ArrayList的最大尺寸限制?
陣列分配的最大大小爲(Integer.MAX_VALUE的 - 8),即; (2^31 - 9)
- 某些虛擬機在陣列中保留一些標題字。嘗試分配較大的數組可能會導致OutOfMemoryError:請求的數組大小超出VM限制。
以下爲ArrayList.java
在第一for循環的源代碼的numo.size()== 0,所以沒有元件在numo加入 –
numo的初始大小是0,因此你的第一環路永遠不會執行因此沒有添加 – ScanQR
我明白了!非常感謝 – SJK