I have a simple arraylist like this: ..
ArrayList<SP> sps = new ArrayList<SP>();
sps.add(new SP("1"));
sps.add(new SP("2"));
sps.add(new SP("3"));
.. When I remove 1 object from that list. What happen next? That list just remove reference of that object and then object auto release that memory zone ( because nothing referenced to that memory of that object) or that object was released directly from that memory zone by that list ?
P/s:Sorry for my bad English.
If you call ArrayList.remove()
the element at the given index is removed from the list (and all elements following it move down one index). The object itself still exists, no memory has been freed yet.
If there are no remaining references to that object in your application after the object has been removed from the list - meaning it's now unused by your program - the Garbage Collector will free up the memory associated with that object automatically so it can be reused.
A couple things happen, both to the ArrayList and the removed object.
When ArrayList.remove()
is called, it does indeed remove reference to that object, from the ArrayList. In addition, the contents proceeding the removed element are shifted down by one.
If there are no other remaining references to that object, the memory allocated for the object is now eligible to be freed in an automated process called Garbage Collection
Example:
ArrayList<Integer> example = otherArrayList; // {2,3,10,6}
example.remove(1); // Remove second element
System.out.println(example.toString());
> [2, 10, 6]
// The space to which '3' is allocated to is now eligible for GC
Example of an object being ineligible for GC:
ArrayList<Integer> example = otherArrayList; // {2,3,10,6}
int ref = example.get(1); // '3' is assigned to ref
example.remove(1); // Remove second element
System.out.println(example.toString());
System.out.print(ref);
> [2, 10, 6]
> 3
/* Java is based on pass-by-value, but it passes references
when we pass existing object values. Which means the
address space allocated for ref (and formerly example.get(1))
is ineligible for GC.
*/
That list just remove reference of that object and then object auto release that memory zone ( because nothing referenced to that memory of that object) or that object was released directly from that memory zone by that list ?
JVM doesn't work in this way.
1) While a object is referenced by a living object in the memory, it is not eligible for GC.
2) Even if an object is not referenced any longer by a living object in the memory, the memory release is not automatic.
It will be released only when a Gargbage collection (minor or full) is performed by the Garbage collector.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With