0

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?

Harry Cho
  • 2,309
  • 4
  • 20
  • 28

1 Answers1

5

First you should note that the size of an array cannot be changed, once created. Changing the size of the underlying array of an ArrayList requires that the entire content of the array be copied to the new array.

When you are increasing the size, you must allocate a larger array, otherwise you could not fit in the new elements. However, it's not worth the performance overhead to copy everything when you remove from the list. Memory is usually a lower concern than performance.

David Frank
  • 5,918
  • 8
  • 28
  • 43