1樓:徐斐然
為什麼減8已經有人回答了,但是事實上ArrayList的最大容量不是Integer.MAX_VALUE-8,而是 Integer.MAX_VALUE。
原始碼如下:
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 limitprivate static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8Increases the capacity to ensure that it can hold at least the
* number of elements specified by the minimum capacity argumentparam minCapacity the desired minimum capacityprivate void grow(int minCapacityoverflow-conscious code
int oldCapacity = elementData.lengthint newCapacity = oldCapacity + (oldCapacity >> 1if (newCapacity - minCapacity < 0newCapacity = minCapacityif (newCapacity - MAX_ARRAY_SIZE > 0newCapacity = hugeCapacity(minCapacityminCapacity is usually close to size, so this is a winelementData = Arrays.copyOf(elementData, newCapacityprivate static int hugeCapacity(int minCapacityif (minCapacity < 0) // overflowthrow new OutOfMemoryErrorreturn (minCapacity > MAX_ARRAY_SIZEInteger.
MAX_VALUEMAX_ARRAY_SIZE;
}如果newCapacity - MAX_ARRAY_SIZE > 0就會呼叫hugeCapacity, 判斷傳入引數minCapacity的大小,當 minCapacity > MAX_ARRAY_SIZE時, ArrayList的最大容量就會設定為Integer.MAX_VALUE。
但困惑的是,本來設定了MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8,為什麼這個時候ArrayList的最大容量又設定為Integer.MAX_VALUE呢?
這樣減8還有什麼意義嗎?
2樓:藍孩子
物件頭里 markword classpointer 佔據一定的空間 classpointer佔四個位元組 markword 32位佔四個位元組,對齊資料可以為0,例項資料為實際陣列的內容
3樓:袁宗宇
原始碼寫了備註:
/*** 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
*/private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
意思應該是有些虛擬機器在陣列中保留了一些頭資訊。避免記憶體溢位!
4樓:知之為知之
是否減8沒那麼重要(只是為了避免一些機器記憶體溢位),最大長度依然是Integer.MAX_VALUE,並不是Integer.MAX_VALUE-8,,如果碰到
/*** 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
*/所說的情況,程式設計師又不知道這種情況依然新增內容,那oom也是在所難免的。。
所以說這個 -8 是為了減少出錯的機率
不知道我說錯了沒,
/*** 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
)private
static
inthugeCapacity
(int
minCapacity)
在ArrayList中的Iterator遍歷中使用list進行刪除操作,卻不會產生異常?
1.程式裡沒有用iterator的remove 而是用list的remove int ArrayList的remove int 的實現 public E remove int index rangeCheck index modCount E oldValue elementData index i...
Java中List String a new List 10 這種寫法的元素型別是List嗎?
代林 首先,Number b new Integer 10 並不是建立了乙個value 10的Integer,而是建立了乙個陣列,這個陣列的長度的10,且理論上只能儲存Integer。想要建立乙個value 10的Integer應該是用Number b new Integer 10 同理,List ...
關於Java中的ConcurrentHashMap的實現原理有大神可以詳細介紹下嗎?
meteor the張 1.7陣列 hashmap,cas rentrantlock 分段鎖1.8陣列 鍊錶 紅黑樹,synchronized cas 優化版的hashmap luoxn28 可以看下這個 mmwx 沒人講1.8版,那我來講講吧。1.8版本相比1.7版本,沒有了分段鎖的概念,轉而使用...