I have a question about how GC works in Java.
Consider the following code:
class C1 {
ArrayList<int> myList = new ArrayList<int>();
public void setList(ArrayList<int> l) {
myList = l;
}
}
func(C1 C) {
ArrayList<int> l1 = new ArrayList<int>();
l1.add(1);
C.setList(l1);
}
main() {
C1 C = new C1();
func(C);
...
}
my question is:
does GC releases ‘l1’ after func() returns or not?
No, it doesn’t, because there’s a root reference (stack variable
C) which has a strong reference (myList), to the newArrayList. Aftermain()returns, then theC1and theArrayListare collectible, because the root reference disappears.