0

After these lines of code:

ArrayList arrayList = new ArrayList(2);
arrayList = new ArrayList(5);

will be first object deleted from memory ?

Tschallacka
  • 27,901
  • 14
  • 88
  • 133

4 Answers4

3

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.)

Andreas
  • 106
  • 5
1

The first object will be candidate for GC (garbage collector) to delete in next of its cycle, it normally is not delete immediately.

VinhNT
  • 1,091
  • 8
  • 13
1

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 to ArrayList(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.

Tschallacka
  • 27,901
  • 14
  • 88
  • 133
0

Nope, it's just eligible for garbage collection.

mauretto
  • 3,183
  • 3
  • 27
  • 28