我正在阅读 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”的引用(studentName
和 students[0]
)。在将 null
分配给 studentName 后,“Peter Smith”仍被 students[0]
关于Java - 为什么将 "null"分配给变量不会使其可用于 GC? (在此代码段中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14756812/