In my Data Structures class we have studies the Java ArrayList class, and how it grows the underlying array when a user adds more elements. That is understood. However, I ca
I have to have another look at ArrayList's source code, but remove
removes the object from the array, and then if the object is not referenced to by any other objects, the GC can delete that object. But the array size is not decreased.
An ArrayList doesn't automatically shrink back, as far as i know. However, you can say something like:
ArrayList al = new ArrayList();
// fill the list for demo's sake
for (int i = 0; i < 1000000; ++i)
{
al.add(i);
}
// now remove all but one element
al.removeRange(1, al.size());
// this should shrink the array back to a decent size
al.trimToSize();
Note, the amount of memory available probably won't change til the GC runs again.
The array size is never reduced automatically. It's very rare to actually have a list that is first filled with a large number of elements, then have it emptied but still kept around. And keep in mind that there must have been enough memory to hold the list (which consists only of references) and its elements - unlikely then that the memory consumed by the empty list would be a problem.
If you really encounter an algorithm bizarre enough that this becomes a problem, you can still free the memory by calling trimToSize() manually.
They don't reduce the underlying array. They simply decrement the size. The reasoning for this is that if you have 1000 elements in an array and delete 1, why reallocate and copy the array? It's hugely wasteful for very little gain.
Basically Java ArrayList
s have two important properties and it's important to understand they are different:
size: how many elements are notionally in the List
; and
capacity: how many elements can fit in the underlying array.
When an ArrayList
expands, it grows by about 50% in size even if you're only adding one element. This is a similar principle in reverse. Basically it comes down to this: reallocating the array and copying the values is (relatively) expensive. So much so that you want to minimize it happening. As long as the notional size is with a factory of about 2 of the array size, it's just not worth worrying about.
There is not much gain by resizing the ArrayList internal array, even you are using ArrayList to hold a large object.
List<LargeObject> list = new ArrayList<LargetObject>();
list will only hold reference to LargeObject instance, and not holding LargeObject instance itself.
Reference doesn't consume much space. (Think it as pointer in C)