[英]What is the purpose of the line “Object oldData[] = elementData;” in the ensureCapacity-method of ArrayList?
[英]oldData in ArrayList implementation
我正在閱讀ArrayList實現,無法理解此方法中的一件事:
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);
}
}
我不明白這個oldData
數組是用來做什么的:
Object oldData[] = elementData;
對我來說,在ensureCapacity
方法內,此局部變量似乎絕對沒有意義。
是的,那條線是完全多余的,沒有重構。
看起來該方法已在Java 7 version
解決,整個方法重構了增加支持數組的邏輯。
作者創建了另一個名為grow()
方法,並將邏輯從版本7中移到那里。
public void ensureCapacity(int minCapacity) {
191 int minExpand = (elementData != EMPTY_ELEMENTDATA)
192 // any size if real element table
193 ? 0
194 // larger than default for empty table. It's already supposed to be
195 // at default size.
196 : DEFAULT_CAPACITY;
197
198 if (minCapacity > minExpand) {
199 ensureExplicitCapacity(minCapacity);
200 }
201 }
202
203 private void ensureCapacityInternal(int minCapacity) {
204 if (elementData == EMPTY_ELEMENTDATA) {
205 minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
206 }
207
208 ensureExplicitCapacity(minCapacity);
209 }
210
211 private void ensureExplicitCapacity(int minCapacity) {
212 modCount++;
213
214 // overflow-conscious code
215 if (minCapacity - elementData.length > 0)
216 grow(minCapacity);
217 }
private void grow(int minCapacity) {
234 // overflow-conscious code
235 int oldCapacity = elementData.length;
236 int newCapacity = oldCapacity + (oldCapacity >> 1);
237 if (newCapacity - minCapacity < 0)
238 newCapacity = minCapacity;
239 if (newCapacity - MAX_ARRAY_SIZE > 0)
240 newCapacity = hugeCapacity(minCapacity);
241 // minCapacity is usually close to size, so this is a win:
242 elementData = Arrays.copyOf(elementData, newCapacity);
243 }
244
245 private static int More ...hugeCapacity(int minCapacity) {
246 if (minCapacity < 0) // overflow
247 throw new OutOfMemoryError();
248 return (minCapacity > MAX_ARRAY_SIZE) ?
249 Integer.MAX_VALUE :
250 MAX_ARRAY_SIZE;
251 }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.