栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

面试问题:符合垃圾收集条件的对象

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

面试问题:符合垃圾收集条件的对象

假设

go
应该是
easyMethod
这样的

class A {    Boolean b;    A easyMethod(A a){        a = null; // the reference to a2 was passed in, but is set to null       // a2 is not set to null - this copy of a reference is!        return a; // null is returned    }    public static void main(String [] args){        A a1 = new A(); // 1 obj        A a2 = new A(); // 2 obj        A a3 = new A(); // 3 obj        a3 = a1.go(a2); // a3 set to null and flagged for GC - see above for why        a1 = null; // so far, a1 and a3 have been set to null and flagged        // Some other pre     }}

有两个对象可以进行垃圾回收(a1和a3)。

b
不是因为它只是对null的引用。没有
Boolean
什么时候进行。

为了避免

// Some other pre
可能出现的无聊的微妙之处,我提出将问题改写为以下内容:

预测并解释以下输出:

class A {    int i;    A(int i) { this.i = i; }    public String toString() { return ""+i; }    A go(A a){        a = null; // the reference to a2 was passed in, but is set to null       // a2 is not set to null - this copy of a reference is!        return a; // null is returned    }    public static void main(String [] args){        A a1 = new A(1); // 1 obj        A a2 = new A(2); // 2 obj        A a3 = new A(3); // 3 obj        a3 = a1.go(a2); // a3 set to null and flagged for GC - see above for why        a1 = null; // so far, a1 and a3 have been set to null and flagged        test(a1);        test(a2);        test(a3);    }    static void test(A a) {        try { System.out.println(a); }         catch(Exception e) { System.out.println((String)null); }    }}

并输出:

c:filesj>javac A.javac:filesj>java Anull2null

后续工作是,此时a1和a3符合GC资格,而a2不符合GC资格。

这个问题的教训是“将对象引用传递给方法并将该引用设置为null不会导致原始引用为空”。那就是面试官试图测试的知识。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/452708.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号