gpt4 book ai didi

Java - 为什么将 "null"分配给变量不会使其可用于 GC? (在此代码段中)

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:34:20 25 4
gpt4 key购买 nike

我正在阅读 oracle 提供的在线教程。其中一个练习题如下:


The following code creates one array and one string object. How many references to those objects exist after the code executes? Is either object eligible for garbage collection?

...
String[] students = new String[10];
String studentName = "Peter Smith";
students[0] = studentName;
studentName = null;
...

Answer: There is one reference to the students array and that array has one reference to the string Peter Smith. Neither object is eligible for garbage collection.

( http://docs.oracle.com/javase/tutorial/java/javaOO/QandE/objects-answers.html )


最后一行肯定意味着 studentName 有资格获得 GC 吗?真的很困惑,我认为这意味着我没有理解“null”的本质以及正确的对象引用,这就是我问的原因。

最佳答案

在将 null 分配给 studentName 之前,有两个对“Peter Smith”的引用(studentNamestudents[0])。在将 null 分配给 studentName 后,“Peter Smith”仍被 students[0]

引用

关于Java - 为什么将 "null"分配给变量不会使其可用于 GC? (在此代码段中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14756812/

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