Given:
11. public void genNumbers(){
12. ArrayList numbers = new ArrayList();
13. for(int i=0; i<10; i++){
14. int value = i * ((int)Math.random());
15. Integer intObj = new Integer(value);
16. numbers.add(intObj);
17. }
18. System.out.println(numbers);
19. }
Which line of code marks the earliest point that an object referenced by intObj becomes a candidate for garbage collection?
A. Line 16 B. Line 17 C. Line 18 D. Line 19 E. The object is NOT a candidate for garbage collection.
答案:D
最佳答案
由于intObj是方法 genNumbers()内部定义的对象,则它的生命周期就在 genNumbers()方法执行结束时终止。由于java具有垃圾回收(garbage collection)机制,在line19处,方法执行完毕,自动运行垃圾回收机制回收对象intObj所占用的资源。
追问
像for循环结束不是也应该运行垃圾回收的吗,为什么不是在line17这个地方运行呢?
回答
Line 18 处语句System.out.println(numbers)打印了numbers数组,而这个数组中的每个元素均是对先前创建的intObj对象的引用。故循环结束时,intObj对象所占资源还需要使用,即它的生命周期还没结束,所以不会被回收。而在 Line 19处,方法运行完毕,生命周期结束,故会进行垃圾回收。