2013-03-28 12 views
2

我有這個目標我已經創建持有引用到一些其他對象:Android我是否需要將每個對象設置爲null時完成使用它?

public class ListHandler { 

    private AppVariables app; //AppVariables instance 
    private Extra extra; //the extra argument represanting the list 
    private ArrayList<FacebookUser> arrayList; //the array list associate with the list given 
    private Comparator<FacebookUser> comparator; //the comparator of the list 
    private String emptyText; //list empty text 

    /** 
    * Constructor - initialize a new instance of the listHandler 
    * @param app the current {@link AppVariables} instance 
    * @param extra the {@link Extra} {@link Enum} of the list 
    */ 
    public ListHandler(AppVariables app, Extra extra) 
    { 
     this.app = app; 
     this.extra = extra; 
     //set the array list to match the list given in the arguments 
     setArrayList(); 
     setComparator(); 
     setEmptyTest(); 
    } 
    /** 
    * Clear all resources being held by this object 
    */ 
    public void clearListHandler() 
    { 
     this.arrayList = null; 
     this.comparator = null; 
     this.app = null; 
     this.emptyText = null; 
     this.extra = null;  
    } 

時使用ListHandler完我已經建立了clearListHandler()方法,以我使用的所有對象設置爲null

有必要嗎?我是否需要清除所有對象以便稍後收集它們垃圾,否則GC會知道此對象已不再使用,因爲已初始化它的對象不再使用?

回答

4

垃圾收集非常聰明,你通常不需要明確地設置對象爲null(儘管它有助於在某些情況下使用位圖時)。

如果對象無法從任何活動線程或任何靜態引用進行訪問,換句話說,如果某個對象的所有引用都爲null,則可以說該對象變爲符合垃圾回收的條件,則該對象變爲符合垃圾回收或GC的條件。循環依賴不被視爲引用,所以如果對象A引用了對象B,並且對象B引用了對象A,並且它們沒有任何其他活動引用,則對象A和B都有資格進行垃圾收集。 通常一個物體變得有資格在Java垃圾收集包括以下情況:

  1. 明確設置爲NULL對象的所有引用如object = null
  2. 在塊內創建對象,並在控件退出該塊時引用超出範圍。
  3. 父對象設置爲空,如果一個對象擁有另一個對象的引用,並且當您設置容器對象的引用爲null,則子對象或包含對象將自動變爲符合垃圾回收條件。
  4. 如果一個對象只有通過WeakHashMap的實時引用,它將有資格進行垃圾回收。

你可以找到更多關於垃圾收集here的詳細信息。

0

否。Dalvik/Java虛擬機將分配內存,並根據需要取消分配內存。

你在做什麼沒有問題,這是沒有必要的。

1

你不應該那樣做。垃圾收集器將在最佳清除所有對象時自動確定。 嘗試閱讀thisthis

+0

Oracle與Android無關。這裏是[Dalvik](http://en.wikipedia.org/wiki/Dalvik_(software))。 – 2013-03-28 14:37:48

+0

但Android仍然是Java,而Dalvik只是另一個JVM。鏈接解釋了任何VM/JVM常見的GC基礎知識。 –

+0

〜「**垃圾收集器將自動確定**」。從什麼時候垃圾收集器可預測和可靠?特別是在Android上... –

相關問題