且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么Object类的clone()方法提供对象的深层副本?

更新时间:2022-12-14 13:25:13

让我们看一下示例中的一部分: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);