这个问题来自Kathy Sierra SCJP 1.6.有多少个对象符合垃圾收集的条件?
根据Kathy Sierra的回答,确实如此C.这意味着两个对象有资格进行垃圾回收.我给出了答案的解释.但为什么c3不符合垃圾收集(GC)的条件?
class CardBoard {
Short story = 200;
CardBoard go(CardBoard cb) {
cb = null;
return cb;
}
public static void main(String[] args) {
CardBoard c1 = new CardBoard();
CardBoard c2 = new CardBoard();
CardBoard c3 = c1.go(c2);
c1 = null;
// Do stuff
} }
Run Code Online (Sandbox Code Playgroud)
何时// Do stuff到达,有多少对象符合GC条件?
回答:
Short包装器对象,该对象也符合条件.在通话时有哪些对象可用于垃圾收集System.gc()?为什么?
public class GCTest {
static class A {
private String myName;
public A(String myName) {
this.myName = myName;
}
}
public static void main(String[] args) {
A a1 = new A("a1");
A a2 = new A("a2");
ArrayList list = new ArrayList();
list.add(a1);
A[] mas = new A[2];
mas[0] = a2;
a2 = a1;
clear(mas);
a1 = null;
a2 = null;
System.gc();
// some code
...
}
private static void clear(A[] mas) {
mas = null;
}
} …Run Code Online (Sandbox Code Playgroud)