class Beta{}
class Alpha {
static Beta b1;
Beta b2;
}
void main (..){
Beta b1 = new Beta();
Beta b2 = new Beta();
Alpha a1 = new Alpha();
Alpha a2 = new Alpha();
a1.b1=b1;
a1.b2=b1;
a2.b2=b2;
a1=null; b1=null; b2 = null;
// do stuff
}
这是一个示例Java证书问题,我似乎并不理解。这个问题询问有多少符合GC条件的对象在第//行做什么,答案是1个对象,而我正在考虑4.有人可以解释一下吗? 因此,b1和a1引用的第一个Beta对象应该符合GC条件,因为b1 = null且a1 = null。不应该由a1引用的Alpha对象是否有资格获得GC,因为a1 = null并且没有其他任何引用它?或者,如果实例Beta b1变量不是静态的,它是否符合条件?
答案 0 :(得分:2)
只有a1符合GC条件。
b1由Alpha的静态成员引用(由于a1.b1 = b1;
)
b2由a2的非静态成员引用(由于a2.b2 = b2;
)
a2引用未设置为null。
答案 1 :(得分:1)
只有一个对象符合GC条件。设1A,2A,1B,2B分别表示A和B的第一和第二对象实例(不是参考)。我在每个步骤后用注释注释了您的代码,以反映当前对这四个对象的引用状态。
class Beta{}
class Alpha {
static Beta b1;
Beta b2;
}
void main (..){
Beta b1 = new Beta();
Beta b2 = new Beta();
Alpha a1 = new Alpha();
Alpha a2 = new Alpha();
//1A <- pointed to by a1
//2A <- pointed to by a2
//1B <- pointed to by b1
//2B <- pointed to by b2
a1.b1=b1;
//1A <- pointed to by a1
//2A <- pointed to by a2
//1B <- pointed to by b1, Alpha.b1
//2B <- pointed to by b2
a1.b2=b1;
//1A <- pointed to by a1
//2A <- pointed to by a2
//1B <- pointed to by b1, Alpha.b1, a1.b2
//2B <- pointed to by b2
a2.b2=b2;
//1A <- pointed to by a1
//2A <- pointed to by a2
//1B <- pointed to by b1, Alpha.b1
//2B <- pointed to by b2, a2.b2
a1=null; b1=null; b2 = null;
//1A <- Eligible for GC
//2A <- pointed to by a2
//1B <- pointed to by Alpha.b1
//2B <- pointed to by a2.b2
// do stuff
}