在JAVA中有"对象的克隆"一说,能不能举个例子,详细地说明对象的克隆是咋回事?

解决方案 »

  1.   

    和克隆小绵羊一个道理,比 new 对象速度快些,另外不用手工复制对象的值,对象分深克隆和浅克隆,浅克隆不会copy非基础对象的值,深克隆就是完全的复制小绵羊. 
      

  2.   

    懒得写了随便帮你找了个demo 浅复制package com.syj;/* 能够被克隆的类要实现Cloneable 接口 */
    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());
    }
    }
      

  3.   

    深复制
    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());
    }
    }
      

  4.   

    2楼 挺好,
    个人理解,深克隆就是: 克隆对象里的所有对象都需要克隆.
    就是完全copy一份新的出来,而不是共享内存地址.
      

  5.   

    要是深复制中的list成员对象在定义的时候申明了final怎么办呀?
    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;
       }