六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 35|回复: 0

Java 克隆学习的一个例子分析

[复制链接]

升级  12.67%

17

主题

17

主题

17

主题

秀才

Rank: 2

积分
69
 楼主| 发表于 2013-2-4 19:56:31 | 显示全部楼层 |阅读模式
package aboutclone;/** * JAVA克隆之浅复制(此例来源于《JAVA编程思想》) * NOTES: * 类里的基本类型(此例中是 Char c)是深复制,自定义(此例是Snake next)或混合类型(如HashMap,ArrayList等)是浅复制. * 所以深复制时要自己写克隆代码克隆每一个自定义类型(此例是Snake next)或混合类型的字段. */public class Snake implements Cloneable {  private Snake next;  private char c;  // Value of i == number of segments  Snake(int i, char x) {    c = x;    if(--i > 0)      next = new Snake(i, (char)(x + 1));  }  void increment() {    c++;    if(next != null)      next.increment();  }  public String toString() {    String s = ":" + c;    if(next != null)      s += next.toString();    return s;  }  public Object clone() {    Object o = null;    try {      o = super.clone();    } catch (CloneNotSupportedException e) {}    return o;  }  public static void main(String[] args) {    Snake s = new Snake(5, 'a');    System.out.println("s = " + s);    Snake s2 = (Snake)s.clone();    System.out.println("s2 = " + s2);        System.out.print("s2==s ? ");    System.out.println(s2==s);//false,有深复制基本类型Char,两对象的第一个字段Char不同,    //但第二个引用类型Snake是指向同一对象,下面的打印输出可以看出.        System.out.print("s2.c==s.c ? ");    System.out.println(s2.c==s.c);//这里深复制了基本类型Char c ,值都是'a',所以为true    System.out.print("s2.next==s.next ? ");    System.out.println(s2.next==s.next);//这里没有深复制自定类型Snake,复制的是引用,但都是指向同一对象,所以为true        s.increment();    System.out.println("after s.increment");        System.out.print("s2.c==s.c ? ");    System.out.println(s2.c==s.c);//false, s2.c=='a' , s.c=='b'        System.out.print("s2.next==s.next ? ");    System.out.println(s2.next==s.next);//true , 浅复制,还是指用同一对象        System.out.println(      "after s.increment, s2 = " + s2);    System.out.println(    "after s.increment, s = " + s);  }}


输出如下:
s = :a:b:c:d:es2 = :a:b:c:d:es2==s ? falses2.c==s.c ? trues2.next==s.next ? trueafter s.increments2.c==s.c ? falses2.next==s.next ? trueafter s.increment, s2 = :a:c:d:e:fafter s.increment, s = :b:c:d:e:f
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表