我需要在使用它时将每个对象设置为null吗?

时间:2013-03-28 14:05:57

标签: android memory-management garbage-collection

我创建了这个对象,它保存了对其他一些对象的引用:

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;      
    }   

我已经构建了clearListHandler()方法,以便在使用null完成后将我正在使用的所有对象设置为ListHandler

有必要吗?我是否需要清除所有对象以便稍后收集垃圾,或者GC是否知道此对象不再使用,因为初始化它的对象不再使用?

3 个答案:

答案 0 :(得分:4)

垃圾收集非常智能,您通常不需要将对象显式设置为null(尽管在某些情况下使用位图时会有所帮助)。

如果某个对象无法从任何活动线程或任何静态引用访问,则该对象符合垃圾收集或GC的条件,换句话说,如果一个对象的所有引用都为空,则可以说该对象符合垃圾回收条件。循环依赖项不计入引用,因此如果对象A具有对象B的引用而对象B具有对象A的引用并且它们没有任何其他实时引用,则对象A和B都将有资格进行垃圾收集。 通常,在以下情况下,对象有资格在Java中进行垃圾收集:

  1. 该对象的所有引用都明确设置为null,例如object = null
  2. 在块内创建对象,并且一旦控制退出该块,引用就会超出范围。
  3. 父对象设置为null,如果对象保存另一个对象的引用,并且当您将容器对象的引用设置为null时,子对象或包含对象将自动符合垃圾回收的条件。
  4. 如果一个对象只有WeakHashMap的实时引用,它将有资格进行垃圾回收。
  5. 您可以在垃圾收集here找到更多详细信息。

答案 1 :(得分:1)

你不应该这样做。垃圾收集器将自动确定何时最好清除所有对象。 请尝试阅读thisthis

答案 2 :(得分:0)

没有。 Dalvik / Java虚拟机将根据需要分配内存和解除分配内存。

你正在做什么没有问题,这是不必要的。