在JAVA中有"对象的克隆"一说,能不能举个例子,详细地说明对象的克隆是咋回事?
解决方案 »
- 用eclipse做开发, 如何reDeploy
- paint(),repaint()的问题。小弟刚学java,现在用他做图形学实验..
- 跳槽好还是不好,进国企还是私企好
- hibernate 问题 为什么插入的数据条数少了
- 请教Hibernate中多对多的问题
- JAVA程序异常问题
- 大家帮以下,jBuilder2006创建webservice
- 【j2nix】连接池经典文章和代码共享
- 请教一个初级问题:J2SE,J2EE,J2ME是什么?是开发工具还是web server(象IIS)
- 在java中,如何用正则表达式表示(){};“”,《》,<>,++,--等诸如此类的符号
- J2EE如何实现人事管理系统
- hibernate 子查询的问题
public class Sheep implements Cloneable {
private String name; public void setName(String arg) {
name = arg;
} public String getName() {
return name;
} public Object clone() throws CloneNotSupportedException {
return super.clone();
} public static void main(String[] args) throws Exception {
/* 得到一个Sheep的实例 */
Sheep first = new Sheep();
first.setName("我是第一只羊");
/* 通过克隆得到另外一个Sheep的实例 */
Sheep second = (Sheep) first.clone();
second.setName("我是另外一只羊");
System.out.println("addr of the first : " + first);
System.out.println("addr of the second : " + second); System.out.println("the name of the first : " + first.getName());
System.out.println("the name of the second : " + second.getName());
}
}
package com.syj;import java.util.ArrayList;
import java.util.List;/* 能够被克隆的类要实现Cloneable 接口 */
public class Sheep implements Cloneable {
private String name;
List list = new ArrayList(); public void setName(String arg) {
name = arg;
} public String getName() {
return name;
} public Object clone() throws CloneNotSupportedException {
Sheep s = (Sheep) super.clone();
s.list = new ArrayList();
return s;
} public static void main(String[] args) throws Exception {
/* 得到一个Sheep的实例 */
Sheep first = new Sheep();
first.setName("我是第一只羊");
/* 通过克隆得到另外一个Sheep的实例 */
Sheep second = (Sheep) first.clone();
second.setName("我是另外一只羊");
System.out.println("addr of the first : " + first);
System.out.println("addr of the second : " + second); System.out.println("the name of the first : " + first.getName());
System.out.println("the name of the second : " + second.getName());
}
}
个人理解,深克隆就是: 克隆对象里的所有对象都需要克隆.
就是完全copy一份新的出来,而不是共享内存地址.
public class Sheep implements Cloneable { final List list = new ArrayList();
。。 public Object clone() throws CloneNotSupportedException {
Sheep s = (Sheep) super.clone();
s.list = new ArrayList(); //这样就会出错了哦!!!!! return s;
}