为什么Object类的clone()方法提供对象的深层副本? [英] Why is the Object class's clone() method giving a deep copy of object?

查看:143
本文介绍了为什么Object类的clone()方法提供对象的深层副本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据JAVA文档,当调用super.clone()时,返回对象的浅表副本.在下面的代码中,我有两个对象 name id ;和一个原始变量 num . 当在第一个对象上调用super.clone()方法时,除了预期的num副本外,它似乎还在创建对象的深层副本(名称和ID).克隆对象obj之后,我更改了它的名称和id字段.如果正在进行浅表复制,则这些更改应反映在克隆的对象中.我说的对吗?

As per the JAVA documentation, the super.clone() when called returns a shallow copy of the object. In the code below I have two objects name and id; and one primitive variable num. When the super.clone() method is called on the first object, it seems to be creating a deep copy of the objects(name and id) in addition to an expected copy of only num. After cloning the object obj, I have changed its name and id fields. These changes should be reflected in the cloned object if a shallow copy was being made. Am I right?

public class Cloning implements Cloneable {
String name;
int num;
Integer id;
Cloning(String name,int num,Integer id)
{
    this.name = name;
    this.num = num;
    this.id = id;
}
public Object clone()
{
    try
    {
        return super.clone();
    }
    catch(CloneNotSupportedException E)
    {
        System.out.println(E.getMessage());
        return null;
    }
}
public void print()
{
    System.out.println(name);
    System.out.println(num);
    System.out.println(id);
}


public static void main(String[] args) {
    // TODO Auto-generated method stub
    Cloning obj = new Cloning("Annu",203,new Integer(3));
    Cloning obj1 = (Cloning)obj.clone();
    obj.name = "Annu_modified";
    obj.num = 204;
    obj.id = new Integer(4);
    obj.print();
    obj1.print();


 }
}

在运行代码时,我得到以下输出:

I get the following output on running the code:

Annu_modified

Annu_modified

204

4

Annu

203

3

推荐答案

让我们看一下示例中的一部分:obj.id = new Integer(4);.在这里,您无需更改id的内部表示,而是将新实例分配给id引用. IntegerString都是不可变的,因此很难感觉到浅拷贝和深拷贝的区别.尝试添加例如ArrayList属性,并且可以对其进行修改,例如添加一个新元素obj.myList.add(13);

Let's look at a section from your example: obj.id = new Integer(4);. Here you're not changing the internal representation of id - you're assigning new instance to the id reference. Both Integer and String are immutable so it's hard to feel the difference of shallow vs deep copy with them. Try to add e.g. an ArrayList attribute and in order to modify it you can e.g. add a new element obj.myList.add(13);

这篇关于为什么Object类的clone()方法提供对象的深层副本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆