我刚刚在Java 6中偶然发现了一行,这个功能对我来说并不清楚.
它是该行Object oldData[] = elementData;
中ensureCapacity(int minCapacity)
的ArrayList方法.oldData
只是看起来是一个局部变量,在方法体的范围内没有用处.我在作业中错过了一些隐藏的魔法吗?
/**
* Increases the capacity of this <tt>ArrayList</tt> instance, if
* necessary, to ensure that it can hold at least the number of elements
* specified by the minimum capacity argument.
*
* @param minCapacity the desired minimum capacity
*/
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);
}
}
Run Code Online (Sandbox Code Playgroud)
小智 5
没有目的,它是一个不断发展的代码和一个邋program的程序员的工件.
Arrays.copyOf()
在JDK 6中引入了.在此之前,代码必须使用System.arrayCopy()
,这需要引用旧数组(我没有方便的JDK 1.5安装,但愿意打赌).
归档时间: |
|
查看次数: |
166 次 |
最近记录: |