0

我的主要问题是在执行该行时真正创建了多少对象

Dozens [] da = new Dozens[3];

以及在 main 函数结束时有多少对象有资格进行垃圾回收

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

4 回答 4

2

执行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
  }
}
于 2012-07-31T08:44:27.543 回答
0

假设没有干预 GC,则创建的三个 Dozen 实例都将符合条件。

没有原始数组的装箱。

于 2012-07-31T08:44:56.590 回答
0

2个实例,但你在想什么:O

da[1] = d; //points 
d = null; //attended. 
da[1] = null; //already null.
于 2012-07-31T08:59:01.570 回答
0

class Dozens contains an int array object. Therefore every time you create a Dozens object two objects are created (one instance of Dozens, which again contains one instance of an int array).

    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]; //one object capable of holding 3 instance 
        da[0] = new Dozens();   //2 object 
        Dozens d = new Dozens(); //2 object 
        da[1] = d;            //no new object d,da[1] point to same d object
        d = null;         //one object for gc
        da[1] null;       //one object for gc
        //do stuff
    }
  }
}
于 2017-03-11T20:58:17.817 回答