After these lines of code:
ArrayList arrayList = new ArrayList(2);
arrayList = new ArrayList(5);
will be first object deleted from memory ?
After these lines of code:
ArrayList arrayList = new ArrayList(2);
arrayList = new ArrayList(5);
will be first object deleted from memory ?
Yes, it will be deleted by the Garbage Collector on its next run. (Assuming you did not assign the reference to another variable in the meantime.)
The first object will be candidate for GC (garbage collector) to delete in next of its cycle, it normally is not delete immediately.
Yes.
ArrayList arrayList = new ArrayList(2);
Java has one reference to
ArrayList(2);
arrayList = new ArrayList(5);
Java has zero reference to
ArrayList(2)
Java has one reference toArrayList(5)
When the Garbage collector runs, it counts the references an object has. If nothing references it anymore, it will be collected and deleted.
Do note, that this does NOT apply to the objects stored in the ArrayList if there's something else referencing it.
Foo bar = new Foo('baz');
Foo baz = new Foo('bar');
ArrayList arrayList = new ArrayList(2);
arrayList.add(bar);
arrayList.add(baz);
arrayList = new ArrayList(5);
In this case, ArrayList(2)
will be unset, but bar
and baz
will not because they still have one reference. You'd have to set those to null or overwrite their variables, or the scope they were in must have expired.
In this case they will get deleted too:
public void fill(ArrayList list) {
Foo bar = new Foo('baz');
Foo baz = new Foo('bar');
arrayList.add(bar);
arrayList.add(baz);
}
ArrayList arrayList = new ArrayList(2);
this.fill(arrayList);
arrayList = new ArrayList(5);
In this case, because the function in which bar
and baz
has expired and there are no more active references to these variables, the bar
and baz
are also eglible for collection.