Clone中存在的浅克隆问题

A.java

package second;



public class A {

    String country;//国家

    String province;//地区

    String city;//城市

    public A(String country,String province,String city){

        this.country = country;

        this.province = province;

        this.city = city;

    }

}

B.java

package second;



public class B implements Cloneable {

    String name;//姓名

    int age;//年龄

    A addr;//定义地址

    /**

     * 构造方法

     * @param name 姓名

     * @param age 年龄

     * @param addr 指向A的地址集

     */

    public B (String name,int age,A addr){

        this.name = name;

        this.age = age;

        this.addr = addr;

    }

    /**

     * 克隆方法

     */

    public Object clone(){

        B handler = null;

        try{

            handler = (B)super.clone();

        }catch(CloneNotSupportedException e){

            e.printStackTrace();

        }

        return handler;

    }

}

C.java

package second;



public class C implements Cloneable {

    public static void main(String[] args){

        A a = new A("中国","北京","西雅图");

        B b = new B("李四",22,a);

        System.out.println(b.name+":"+b.addr.country+b.addr.province+b.addr.city);

        B bclone = (B)b.clone();

        bclone.addr.country = "美国";

        bclone.addr.province = "佛罗里达州";

        bclone.addr.country = "罗德里格斯";

        System.out.println(bclone.name+":"+bclone.addr.country+bclone.addr.province+bclone.addr.city);

        System.out.println(b.name+":"+b.addr.country+b.addr.province+b.addr.city);

    }

}

 

输出:

李四:中国北京西雅图

李四:罗德里格斯佛罗里达州西雅图

李四:罗德里格斯佛罗里达州西雅图

 

PS::可见即使通过克隆的方法,如果有变量指向的是一个可变的变量;原对象跟克隆后的对象中的可变对象(变量)仍然是指向的同一个内存地址:;

解决方法,重新构造一组可变的变量,这样就不会覆盖原地址的数据

C.java

package second;



public class C implements Cloneable {

    public static void main(String[] args){

        A a = new A("中国","北京","西雅图");

        B b = new B("李四",22,a);

        System.out.println(b.name+":"+b.addr.country+b.addr.province+b.addr.city);

        B bclone = (B)b.clone();

        A a1 = new A("美国","佛罗里达州","罗德里格斯");

        bclone.addr = a1;

        System.out.println(bclone.name+":"+bclone.addr.country+bclone.addr.province+bclone.addr.city);

        System.out.println(b.name+":"+b.addr.country+b.addr.province+b.addr.city);

    }

}

结果:

李四:中国北京西雅图

李四:美国佛罗里达州罗德里格斯

李四:中国北京西雅图

 

你可能感兴趣的:(clone)