In ArrayList class of java.util package I notice following lines of code
private Object[] grow(int minCapacity) {
int oldCapacity = elementData.length;
if (oldCapacity > 0 || elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {//Line3
int newCapacity = ArraysSupport.newLength(oldCapacity,//Line 4
minCapacity - oldCapacity, /* minimum growth */
oldCapacity >> 1 /* preferred growth */);
return elementData = Arrays.copyOf(elementData, newCapacity);
} else {
return elementData = new Object[Math.max(DEFAULT_CAPACITY, minCapacity)];
}
}
In line 3 we have an if statement. The construct is such that else block is executed only when oldCapacity == 0
and elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
. Now, because of line 2 and condition that DEFAULTCAPACITY_EMPTY_ELEMENTDATA
is private,static final oldCapacity == 0
is redundant. The entire piece of code can be simplified to
private Object[] grow(int minCapacity) {
int oldCapacity = elementData.length;
if (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
int newCapacity = ArraysSupport.newLength(oldCapacity,
minCapacity - oldCapacity, /* minimum growth */
oldCapacity >> 1 /* preferred growth */);
return elementData = Arrays.copyOf(elementData, newCapacity);
} else {
return elementData = new Object[Math.max(DEFAULT_CAPACITY, minCapacity)];
}
}
is it a miss from developer or am I wrong somewhere?
I wanted to understand the usage of DEFAULTCAPACITY_EMPTY_ELEMENTDATA
in ArrayList implementation. Since, it’s a widely used library I would expect it to have really efficient code. I don’t think there is anything wrong in my reasoning. If the community helps me we can make this library faster.
2