V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
proxytoworld
V2EX  ›  问与答

打扰一下,这个 Java 代码为什么报空指针错误啊,实现深 clone

  •  
  •   proxytoworld · 2020-11-16 19:07:09 +08:00 · 511 次点击
    这是一个创建于 1293 天前的主题,其中的信息可能已经有所发展或是发生改变。

    代码:

    package deepcopy;
    
    public class DeepCopy {
        static class Body implements Cloneable {
            public Head head;
    
            public Body() {
            }
    
            public Body(Head head) {
                this.head = head;
            }
            //重写 clone 方法
            @Override
            protected Object clone() throws CloneNotSupportedException {
                Body newBody = (Body) super.clone();
                newBody.head = (Head) head.clone();
                return newBody;
            }
        }
    
        static class Head implements Cloneable {
            public Face faces;
    
            public Head() {
            }
    
            public Head(Face face) {
                this.faces = face;
            }
            //重写 clone 方法
            @Override
            protected Object clone() throws CloneNotSupportedException {
                Head head = (Head) super.clone();
                head.faces = (Face)this.faces.clone();
                return head;
            }
        }
    
        static class Face implements Cloneable{
            //重写 clone 方法
            @Override
            protected Object clone() throws CloneNotSupportedException{
                return super.clone();
            }
        }
    
        public static void main(String[] args) throws CloneNotSupportedException {
            Body body = new Body(new Head());
            Body body1 = (Body) body.clone();
            System.out.println(body == body1);
            System.out.println(body.head == body1.head);
            System.out.println(body.head.faces == body1.head.faces);
            System.out.println(body.head);
            System.out.println(body1.head);
        }
    }
    
    1 条回复    2020-11-16 19:27:19 +08:00
    lwlizhe
        1
    lwlizhe  
       2020-11-16 19:27:19 +08:00
    额,不知道是不是全部代码……

    不过我感觉这种空指针应该是最简单的错误了哈……这种问题自己看下报错信息……我感觉这种问题没多大意义……

    回正题

    乍看应该是 head 中 face 为空导致的,跟拷不拷贝好像没什么关系,body.clone 调用了 head.clone,head.clone 调用了 face.clone,然而 face 是空的
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   1868 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 16:21 · PVG 00:21 · LAX 09:21 · JFK 12:21
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.