本文介绍了垃圾收集模拟OCPJP考试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

i3 = null时,有四个对象符合垃圾回收的条件; 在下面显示的类中执行。我添加了评论来解释我是如何得到这个答案的。我的推理是否正确?

Four objects are eligible for garbage collection when i3 = null; is executed in the class shown below. I've added comments to explain how I got this answer. Is my reasoning correct?

public class Icelandic extends Horse{
    public void makeNoise(){
        System.out.println("vinny");
    }

    public static void main(String args[]){
        /**
         * 2 objects created
         */
        Icelandic i1 = new Icelandic();

        /**
         * 2 objects created
         */
        Icelandic i2 = new Icelandic();

        /**
         * 2 objects created
         */
        Icelandic i3 = new Icelandic();

        /**
         * i3 is now pointing at i1, original Icelandic() referred to by i3 now
             * has no reference -  2 objects now have no reference
         */
        i3 = i1;

        /**
         * i3 is now pointing at i1, original Icelandic() referred to by i1 now
             * has no reference -  2 objects now have no reference
         */
        i1 = i2;

        /**
         * Total of six objects created, 4 objects no longer have a reference so 4
             * can be garbage collected.
         * 
         * Setting to null below doesn't make any difference to garbage collector
             * as objects now do not have a reference
         */
        i2 = null;
        i3 = null;
    }
}

interface Animal {
    void makeNoise();
}

class Horse implements Animal{
    Long weight = 1200L;

    public void makeNoise() {
        System.out.println("whinny");
    }    
}


推荐答案

这些是您的计划的步骤:

These are steps of your program:

    Icelandic i1 = new Icelandic();
    Icelandic i2 = new Icelandic();
    Icelandic i3 = new Icelandic();
    i3 = i1;
    i1 = i2;
    i2 = null;
    i3 = null;

因此,最后一个图表得出结论,只有2个对象可以进行垃圾回收。
我希望我很清楚。您可以将对象名称视为对象的引用。

So the last diagram concludes that only 2 objects are ready for garbage collection.I hope I am clear. You can see object names as references to the objects.

编辑:

正如BalusC所说,长重= 1200L也是对象。因此,i1和i3各有2个对象是合格的或垃圾收集。因此,所有4个对象都符合条件或垃圾回收。

As said by BalusC, Long weight = 1200L is also object. So 2 more objects each for i1 and i3 are eligible or garbage collections. So in all 4 objects are eligible or garbage collection.

这篇关于垃圾收集模拟OCPJP考试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 06:55