跳至主要內容
  • Hostloc 空間訪問刷分
  • 售賣場
  • 廣告位
  • 賣站?

4563博客

全新的繁體中文 WordPress 網站
  • 首頁
  • 打扰一下,这个 Java 代码为什么报空指针错误啊,实现深 clone
未分類
31 10 月 2020

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

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

資深大佬 : proxytoworld 2

代码:

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)

  • 資深大佬 : lwlizhe

    额,不知道是不是全部代码……

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

    回正题

    乍看应该是 head 中 face 为空导致的,跟拷不拷贝好像没什么关系,body.clone 调用了 head.clone,head.clone 调用了 face.clone,然而 face 是空的

文章導覽

上一篇文章
下一篇文章

AD

其他操作

  • 登入
  • 訂閱網站內容的資訊提供
  • 訂閱留言的資訊提供
  • WordPress.org 台灣繁體中文

51la

4563博客

全新的繁體中文 WordPress 網站
返回頂端
本站採用 WordPress 建置 | 佈景主題採用 GretaThemes 所設計的 Memory
4563博客
  • Hostloc 空間訪問刷分
  • 售賣場
  • 廣告位
  • 賣站?
在這裡新增小工具