For add()
method, the implementation is such that the elementData\[\]
array's size grows as needed. However, looking at the remove()
method, it does not shrink the size as elements are removed.
I tested using a simple code and the elementData[]
starts out with 10
and grows. However, when I delete all the elements using remove()
method, the size of elementData[]
stays at the point where I finished adding all elements.
int testSize = 10000000;
ArrayList<Integer> alist = new ArrayList<Integer>();
// size of elementData[] is 10
for(int i = 0; i < testSize; i++) {
alist.add(i);
}
// size of elementData[] is 13845150
for(int i = alist.size()-1; i >= 0; i--) {
alist.remove(i);
}
// size of elementData[] remains at 13845150
Isn't this wasting memory?