I've been working on a class in Java for a data structures assignment where we manually implement an array list, here is the method I created in the class that increases the capacity of the array list:
public void increaseCapacity () {
Object[] tmp = new Object[_maxItems*2];
if (_listItems !=null) {
System.arraycopy(_listItems, 0, tmp, 0, _maxItems);
_maxItems = _listItems.length;
}
_listItems = tmp;
} // Increase size of list (doubles in size each time)
with _listItem
being the object array that I add elements to / resize ect.. , I understand how using the temporary array can copying its contents back into _listItem
increases size but what I don't understand is what happens to the original _listItem
array that was of the smaller size.
When the tmp
object array is copied into _listItem
is new memory created for the variable _listItem
and the tmp
is copied into that? Or is the same memory used with extra space "appended" onto it when tmp
is copied into _listItem
? (I hope that reads well).
Essentially is the array _listItem
a new variable when tmp
is copied into it and if so how has its size increased without me explicitly doing so?
I feel this has something to do with the was Java manages memory but I can't wrap my head round it.
When you do:
Object[] tmp = new Object[_maxItems*2];
You are creating a new array of Object
and a variable tmp
that references it.
Later, when you do:
_listItems = tmp;
two things happen:
_listItems
is not referenced by it anymore. If it is not referenced by another variable elsewhere, then it will be garbage collected later.tmp
is now also referenced by _listItems
. No copy is performed.Java has a Garbage Collector mechanism. Every variable (except the variables of integral types like int
, float
, etc.) actually hold references to objects. These objects can be arrays or other plain objects, like String. Everytime an object is not referenced by any variable, the Garbage Collector can free the memory that the object uses. It will not necessarily do so immediately for performance reason, it can wait for a time where some memory will be required to create another object.