2013-06-02 79 views
4

以下代碼創建一個數組和一個字符串對象。在java中刪除對象

現在我的問題是

  1. 代碼執行後有多少引用這些對象是否存在?
  2. 爲什麼?

這裏是我的代碼

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

我想答案只有一個目標,即students
但根據Oracle docsNeither object is eligible for garbage collection

我應該如何推斷出答案嗎?

+3

沒有這些變量超出範圍這4條線路經過這麼沒什麼可享有我猜。該代碼在什麼情況下執行? – Djon

回答

10

代碼執行後對這些對象存在多少個引用?

  • 一個參照本發明的String[],通過表達students獲得。
  • String的一個引用,可通過表達式students[0]獲得。

爲什麼?

本質上,答案是對象而不是變量可以有資格進行垃圾回收。

就你而言,你已經將字符串(它是一個對象)的引用複製到數組的第一個插槽中。即使在清除(設置爲null)初始變量之後,該同一對象仍可從您的代碼中看到,通過另一個名稱(和「名稱」,這裏我的意思是「表達式」,如上所述)。這就是爲什麼字符串仍然不符合垃圾回收的條件。


爲了比較,考慮你的代碼,而第三行:

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

在這種情況下,該字符串"Peter Smith"確實是符合垃圾收集你所期望的,因爲它不是獲得了通過任何表達。


(以上所有關注Java語言和留下任何可能的JVM優化了一邊。)

+0

如果變量[引用]沒有資格,那麼他們永遠提醒堆棧? – Lokesh

+0

@loki局部變量也稱爲「自動變量」,因爲它們的空間在執行流程期間會自動回收(當它們超出範圍時)。大多數現代語言都是這種情況,因爲這些變量的空間是靜態分配的。另一方面,垃圾收集通常指的是自動管理*動態分配的內存。 –

+0

@Theodoros非常感謝..你的回答是完美的.. 你能爲我提供你的電子郵件ID嗎? (只是在SO之外進行討論) 或pm我在snackysrikanth [at] gmail.com - 謝謝:) –

3

這裏"Peter Smith是一個對象,並分配給students[0]所以它不能被垃圾收集和studentName=null,它指向沒有,所以沒有嘗試垃圾收集它。

所以,兩者都不能被垃圾收集。

1

你是對的,students是一個對象,但它是一個String數組類型的對象。在一個數組中,數組中的每個元素都可以引用其他對象,並且第一個元素`students [0]'引用包含「Peter Smith」的字符串對象,這樣對象仍然被引用,因此不符合垃圾回收的條件。當學生超出範圍並且有資格獲得GC本身時,字符串對象也會如此。

1

students被實例化,然後改變,所以沒有理由收集,因爲我們仍然有一個參考。 studentName被實例化,那麼引用被分配給students,所以當它在最後一行被取消引用時,對該對象的引用仍然存在於數組中,這就是爲什麼GC沒有收集任何東西。

+0

「學生」數組稍後改變的事實並不是在代碼執行後仍然活着的原因。 –

+0

我從來沒有說過,我列出了陣列發生了什麼,因爲沒有涉及解引用,我然後得出結論,它不符合GC的條件。 – Djon

3

對象可以有多個引用,即使您將studentName的引用設置爲null,String對象仍然被student[0]引用。所以字符串"Peter Smith"不能被垃圾收集。

4
String[] students = new String[10]; 
// 1. One object (array of String, 1 reference to it - students) 
String studentName = "Peter Smith"; 
// 2. Two objects (array from (1), string 'Petter Smith'), two references 
// (students from (1), studentName that refers String object) 
students[0] = studentName; 
// 3. Two objects (the same as (2)), 3 references (in addition to references (2) 
// first element of students array refers to the same object as studentName 
studentName = null; 
// Two objects (Array and String "Peter Smith"), two references (one is array, 
// another is students[0] 
// Neither of them can be marked for garbage collection at this point 
// (Array and String "Peter Smith") 

我希望有道理。

+0

這是很好的解釋..謝謝.. :) –