简体   繁体   English

垃圾收集

[英]Garbage Collection

I found this question in one of the Java dumps and I would like to know how many object would be available after more code here 11 comment in the following code 我在其中一个Java转储中发现了这个问题,我想知道在more code here 11之后more code here 11多少对象可供使用more code here 11以下代码中的注释

public class Tahiti {
    Tahiti t;
    public static void main(String[] args) {
        Tahiti t = new Tahiti();
        Tahiti t2 = t.go(t);
        t2 = null;
        // more code here 11
    }
    Tahiti go(Tahiti t) {
        Tahiti t1 = new Tahiti();
        Tahiti t2 = new Tahiti();
        t1.t = t2;
        t2.t = t1;
        t.t = t2;
        return t1;
    }
}

My answer was one since the object reference by t2 object under main method has been set to null and because of that there isnt any reference pointing to that object but i found out that answer is 0 我的答案是一个,因为在main方法下t2对象的对象引用已被设置为null,因此没有任何引用指向该对象,但我发现答案是0

Could anyone help me on this? 有人可以帮我吗? thanks 谢谢

How many objects are available? 有多少个物品?

All three. 三个全部。 Variable t in main points directly to the first. 主要点的变量t直接到第一个。 That object's t field points at a second object, which was known as t2 within the go method. 该对象的t字段指向第二个对象,在go方法中称为t2 That object's t field points at the third object, known as t1 within the go method. 该对象的t字段指向第三个对象,在go方法中称为t1

Proof: 证明:

System.out.println(t);
System.out.println(t.t);
System.out.println(t.t.t);

Assuming the VM manages to give all three created objects unique hashcodes (which it generally should), you should see something like: 假设VM设法为所有三个创建的对象提供唯一的哈希码(它通常应该这样),你应该看到类似的东西:

Tahiti@107ebe1
Tahiti@10f11b8
Tahiti@544ec1

You could give the objects a String name; 您可以为对象指定一个String name; field to make distinguishing them easier. 领域使他们更容易区分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM