I’ve just stumbled over a line in Java 6 which function is not clear to me.
It is the line Object oldData[] = elementData; in the ensureCapacity(int minCapacity) method of ArrayList. oldData just appears to be a local variable with no uses in the scope of the method body. Am I missing some hidden magic in the assignment?
/**
* 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);
}
}
No purpose, it’s an artifact of evolving code and a sloppy programmer.
Arrays.copyOf()was introduced in JDK 6. Prior to that, the code would have to useSystem.arrayCopy(), which required a reference to the old array (I don’t have a JDK 1.5 installation handy, but would be willing to bet on this).