Java对象克隆Clone
来源:优易学  2009-12-4 10:21:26   【优易学:中国教育考试门户网】   资料下载   IT书店
文章页内部300*250广告位

  java里面的对象克隆:实际存在的对象拷贝几份!

  即将一个实际的对象进行多份拷贝

  Code highlighting produced by Actipro CodeHighlighter (freeware)

  http://www.CodeHighlighter.com/

  package xsocket.server;

  public class Test implements Cloneable {

  private String name;

  public void setName(String arg) {

  this.name = arg;

  }

  public String getName() {

  return this.name;

  }

  public Object clone() throws CloneNotSupportedException {

  return super.clone();

  }

  public static void main(String[] args) throws CloneNotSupportedException {

  Test shepp = new Test();

  shepp.setName("first");

  System.out.println(shepp.getName());

  Test sheppclone = (Test)shepp.clone();  //对象拷出来一份副本

  System.out.println(sheppclone.getName());

  System.out.println("shepp == sheppclose" + (shepp == sheppclone));

  }

  }

  要知道== 表示的是同一份对象。这里面的内存位置是不一样的哦。所以==就不一样了!

  Code highlighting produced by Actipro CodeHighlighter (freeware)

  http://www.CodeHighlighter.com/

  package xsocket.server;

  public class Test implements Cloneable {

  private String name;

  public void setName(String arg) {

  this.name = arg;

  }

  public String getName() {

  return this.name;

  }

  public Object clone() throws CloneNotSupportedException {

  return super.clone();

  }

  public static void main(String[] args) throws CloneNotSupportedException {

  Test shepp = new Test();

  shepp.setName("first");

  Test shepp2 = shepp;  //只是将两个值指向了同一个对象了所以会相互影响到对方的值!

  System.out.println(shepp2.getName());

  Test shepp3 = (Test)shepp.clone();//再做一个实际的副本出来就不会相互影响的!

  shepp3.setName("another");

  System.out.println(shepp3.getName());

  System.out.println(shepp.getName());

  }

  }

  输出:

  first

  another

  first

  (这就是拷贝的好处了!)

  要考虑一下什么时候用浅clone什么时候用深clone

责任编辑:小草

收藏此页】【 】【打印】【回到顶部
等级考试课程列表页595*300
文章搜索:
 相关文章
计算机底部580*90广告
文章页右侧第一330*280广告
计算机文章页资讯推荐
热点资讯
文章页330尺寸谷歌广告位
资讯快报
热门课程培训