Android 使用完后是否需要将每个对象设置为 null?

Asa*_*evo 2 android garbage-collection memory-management

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

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;      
    }   
Run Code Online (Sandbox Code Playgroud)

我构建了该clearListHandler()方法,以便null在使用完ListHandler.

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

Rag*_*ood 5

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

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

  1. 该对象的所有引用显式设置为 null,例如 object = null
  2. 对象是在块内创建的,一旦控制退出该块,引用就会超出范围。
  3. 父对象设置为 null,如果一个对象持有另一个对象的引用,并且当您将容器对象的引用设置为 null 时,子对象或包含的对象将自动符合垃圾回收的条件。
  4. 如果一个对象仅通过 WeakHashMap 具有实时引用,则它将有资格进行垃圾回收。

您可以在此处找到有关垃圾收集的更多详细信息。