我正在研究OCA认证,不知道如何理解一个问题的答案。
public class Test {
public static void main(String[] args){
Student s1 = new Student("o1");
Student s2 = new Student("o2");
Student s3 = new Student("o3");
s1=s3;
s3=s2;
s2=null;
//HERE
}
}问题是在//HERE点之后哪个对象可用于垃圾收集。
在线测试提供的答案是:一个对象(o1)。
有人能解释一下为什么吗?
发布于 2021-07-09 08:52:30
考虑一个简单的班级学生。
步骤1 :
Student s1 = new Student("s1");
Student s2 = new Student("s2");
Student s3 = new Student("s3");s1,s2,s3引用堆空间中的3个对象

步骤2 :
Student s1 = s3; s1现在引用堆空间中的s3对象
堆空间中的对象s1丢失了他的引用

步骤3 :
Student s1 = s3;
Student s3 = s2;可变s1引用s3堆空间
可变s3引用s2堆空间

步骤4 :
Student s1 = s3;
Student s3 = s2;
Student s2 = null;可变s1引用s3堆空间
可变s3引用s2堆空间
变量s2失去了引用(空指针)

结论:
第11行之后的,有一个对象符合垃圾收集的条件。
发布于 2021-07-09 14:35:40
每次出现这类问题时,答案都是一样的:在注释HERE之后,每个对象都有资格进行垃圾收集。该行之后不使用任何东西,因此不存在对任何对象的强引用,因此所有东西都有资格使用GC。不幸的是,这类问题只有在考试中获得正确的“分数”时才有意义,因此人们会按照自己的方式来学习。现实情况是,如果没有更广泛的可达性背景,它们只会混淆用户,海事组织。
想想看-在那个评论之后,是否有任何对你的对象的实时引用?不是的。因此,是否每个实例都有资格获得GC?是。请注意,在该注释之后,而不是在方法结束之后,它们是合格的。不要将范围混和在一起。
发布于 2021-07-09 08:48:33
Student s1 = new Student("o1");
Student s2 = new Student("o2");
Student s3 = new Student("o3");
s1=s3; // The "s1" variable now points to the object referenced to by s3, ie "o3"
s3=s2; // The "s3" variable now points to the object referenced to by s2, ie "o2"
s2=null; // The "s2" variable points to nothing在执行结束时,对象"o3“和"o2”由变量("s1“和"s3”)引用。因此,任何变量都不指向对象"o1“,垃圾收集器可以销毁该对象。
https://stackoverflow.com/questions/68313719
复制相似问题