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

标签 java variables null garbage-collection

我正在阅读 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/

相关文章:

C 宏传递数字而不是变量

c - C 函数中的变量

C# 6.0 和 null

java - 我如何才能从任何类访问这个数组?

java - 将 keylistener 添加到 CardLayout 中的面板

java - 如何将文本向左移动?

javascript - 定义变量,如 a、b、c

SQL 查询按具有空值的多个列排序

javascript - IE 中奇怪的 "Null or not an object"错误

java - 设置要使用 BufferedReader 读取的文件的相对路径