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

问题描述

我正在准备,并且我被困在以下模拟考题中:



鉴于:

  3。 interface Animal {void makeNoise(); } 

4. class Horse实现Animal {
5.长重= 1200L;
6. public void makeNoise(){System.out.println(whinny); }
7.}

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

10. public static void main(String [] args){
11. Icelandic i1 = new Icelandic();
12.冰岛i2 =新冰岛();
12.冰岛i3 =新冰岛();
13. i3 = i1; i1 = i2; i2 = null; i3 = i1;
14.}
15.}

当第14行到达时,许多对象符合垃圾收集器的条件吗?



A。 0



B。 1

C。 2



D。 3

E。 4



F。 6



他们的正确答案是E,即四个对象,但我不确定为什么。从我的角度来看,i2及其重量将有资格进行垃圾回收。

解决方案

让我们打电话给 Icelandic()第11行 IceA ,第12行 IceB 等等。



创建后

  i1 = IceA 
i2 = IceB
i3 = IceC

在 i3 = i1

  i1 = IceA 
i2 = IceB
i3 = IceA
$ b $ i1 = i2

  i1 = IceB 
i2 = IceB
i3 = IceA



i2 = null

  i1 = IceB 
i2 = null
i3 = IceA

在 i3 = i1后

  i1 = IceB 
i2 = null
i3 = IceB $ b因此只有在第12行创建的 Icelandic()>

遗迹。现在,每个 Icelandic()都有一个长权重,所以 IceA 和 IceC 现在未被引用,意味着4个对象( IceA , IceA.weight , IceC , IceC.weight )可用于GC。






其他问题:


  1. args 仍然是 args ,它们在这个问题中不会超出范围

  2. Long weight 没有静态声明,因此每个类的实例都有一个 weight 对象。


I am preparing for OCPJP, and I got stuck at the following mock exam question:

Given:

3. interface Animal { void makeNoise(); }

4. class Horse implements Animal {
5.     Long weight = 1200L;
6.     public void makeNoise() { System.out.println("whinny"); }
7. }

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

10.    public static void main(String[] args) {
11.        Icelandic i1 = new Icelandic();
12.        Icelandic i2 = new Icelandic();
12.        Icelandic i3 = new Icelandic();
13.        i3 = i1; i1 = i2; i2 = null; i3 = i1;
14.    }
15. }

When line 14 is reached, how many objects are eligible for the garbage collector?

A. 0

B. 1

C. 2

D. 3

E. 4

F. 6

Their correct answer is E, i.e. four objects, but I'm not sure why. From my point of view, i2 and its weight will get eligible for garbage collection. Perhaps I'm missing something, please advise.

解决方案

Lets call Icelandic() on line 11 IceA, line 12 IceB, and so forth.

After creation

i1 = IceA
i2 = IceB
i3 = IceC

After i3 = i1

i1 = IceA
i2 = IceB
i3 = IceA

After i1 = i2

i1 = IceB
i2 = IceB
i3 = IceA

After i2 = null

i1 = IceB
i2 = null
i3 = IceA

After i3 = i1

i1 = IceB
i2 = null
i3 = IceB

So only the Icelandic() created on line 12 remains. Now, each Icelandic() has a Long weight, so IceA and IceC are now unreferenced, meaning 4 objects (IceA, IceA.weight, IceC, IceC.weight) are available for GC.


Other issues:

  1. args is still args, they are not counting going out of scope in this question
  2. Long weight is not declared statically, so each instance of the class has a weight object.

这篇关于Java中垃圾收集的合格变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 16:11