我的主要问题是在执行该行时实际上创建了多少个对象

Dozens [] da = new Dozens[3];


在主函数末尾有多少个对象可以进行垃圾回收

class Dozens {
  int[] dz = {1,2,3,4,5,6,7,8,9,10,11,12};
}

public class Eggs {
  public static void main(String[] args) {
    Dozens [] da = new Dozens[3];
    da[0] = new Dozens();
    Dozens d = new Dozens();
    da[1] = d;
    d = null;
    da[1] = null;
    // do stuff
  }
}

最佳答案

执行Dozens [] da = new Dozens[3];后,将创建一个对象。 main方法完成后,如果不创建使用main中创建的对象的另一个线程,则您创建的所有对象将可用于垃圾回收。

public class Eggs {
  public static void main(String[] args) {
    Dozens [] da = new Dozens[3]; //one array object created
    da[0] = new Dozens(); // one Dozens object created
    Dozens d = new Dozens(); //one Dozens object created
    da[1] = d;
    d = null; //nothing available for gc here, as there is still a referrence to that Dozens object (da[1])
    da[1] = null; //da[1] available for gc
    // do stuff
  }
}

关于java - 到达main的最后一行时,有多少个对象可以进行垃圾回收?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11736199/

10-12 15:00