符合垃圾收集条件的对象 [英] Objects eligible for garbage collection

查看:116
本文介绍了符合垃圾收集条件的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题来自 Kathy Sierra SCJP 1.6 。有多少对象有资格进行垃圾收集?

This question was taken from Kathy Sierra SCJP 1.6. How many objects are eligible for garbage collections?

根据Kathy Sierra的回答,它是 C 。这意味着两个对象有资格进行垃圾回收。我给出了答案的解释。 但为什么 c3 不符合垃圾收集(GC)?

According to Kathy Sierra's answer, it is C. That means two objects are eligible for garbage collection. I have given the explanation of the answer. But why is c3 not eligible for garbage collection (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
} }

//达到了什么,有多少对象符合GC条件?

When // Do stuff is reached, how many objects are eligible for GC?


  • A:0

  • B:1

  • C:2

  • D:编译失败

  • E:无法知道

  • F:运行时抛出异常

  • A: 0
  • B: 1
  • C: 2
  • D: Compilation fails
  • E: It is not possible to know
  • F: An exception is thrown at runtime

答案:


  • C是正确的。只有一个CardBoard对象(c1)符合条件,但它有一个关联的 Short 包装器对象,该对象也符合条件。

  • A,B基于以上内容,D,E和F不正确。 (目标7.4)

  • C is correct. Only one CardBoard object (c1) is eligible, but it has an associated Short wrapper object that is also eligible.
  • A, B, D, E, and F are incorrect based on the above. (Objective 7.4)

推荐答案

没有任何对象存在 c3 指向。构造函数只被调用两次,两个对象,每个对象由 c1 c2 指向。 c3 只是一个引用,除了空指针之外从未分配任何内容。

No object ever existed that c3 points to. The constructor was only called twice, two objects, one each pointed to by c1 and c2. c3 is just a reference, that has never been assigned anything but the null pointer.

引用 c3 ,当前指向null,不会超出范围并从堆栈中删除,直到超过main方法结束时的右括号。

The reference c3, that currently points to null, won't go out of scope and be removed from the stack until the closing brace at the end of the main method is crossed.

最初分配给 c1 的对象无法访问,因为设置了 c1 引用为null,但 c2 引用尚未更改,因此分配给它的对象仍可通过 c2 参考。

The object originally assigned to c1 is unreachable because the c1 reference was set to null, but the c2 reference has not been changed, so the object assigned to it is still reachable from this scope via the c2 reference.

这篇关于符合垃圾收集条件的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆