gpt4 book ai didi

java - 未被引用的对象能否被再次引用?

转载 作者:行者123 更新时间:2023-11-29 05:12:50 25 4
gpt4 key购买 nike

正如主题所说:未引用的对象可以再次引用吗?

我在 http://www.javatpoint.com/corejava-interview-questions-4 遇到了这个问题Q120。我为此尝试使用谷歌搜索,但没有找到任何链接。我们实际上是怎么做到的?

最佳答案

下面的例子不是一个“在野外”的例子,但它演示了一个未引用对象如何被 finalize 方法“复活”。这可能只会发生一次。如果第一个实例的对象第二次变为未引用,则不会再次调用 finalize() 方法。

public class Resurrect {

static Resurrect resurrect = null;

public static void main(String[] args) {
Resurrect localInstance = new Resurrect();
System.out.println("first instance: " + localInstance.hashCode());

// after this code there is no more reference to the first instance
localInstance = new Resurrect();
System.out.println("second instance: " + localInstance.hashCode());

// will (in this simple example) request the execution of the finalize() method of the first instance
System.gc();
}

@Override
public void finalize() {
resurrect = this;
System.out.println("resurrected: " + resurrect.hashCode());
}
}

关于java - 未被引用的对象能否被再次引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27743096/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com