Is clone() in java shallow copy?

Is clone() in java a shallow copy?

Eventually this gets to the clone() method of Object (the uppermost class), which creates a new instance of the same class as the object and copies all the fields to the new instance (a "shallow copy").

I read this from wikipedia.

I don't understand why it is a shallow copy. clone() will create a new instance with all fields. Is this just a deep copy? confused. Need some explanation for me.


The default Object.clone() is indeed a shallow copy. However, it's designed to throw a CloneNotSupportedException unless your object implements Cloneable .

And when you implement Cloneable , you should override clone() to make it do a deep copy, by calling clone() on all fields that are themselves cloneable.


As an aside, I'm surprised nobody has mentioned Joshua Bloch's views on Cloneable

If you've read the item about cloning in my book, especially if you read between the lines, you will know that I think clone is deeply broken. There are a few design flaws, the biggest of which is that the Cloneable interface does not have a clone method. And that means it simply doesn't work: making something Cloneable doesn't say anything about what you can do with it. Instead, it says something about what it can do internally. It says that if by calling super.clone repeatedly it ends up calling Object's clone method, this method will return a field copy of the original.


clone() creates copy of all fields. Java have primitive types and refences - when you clone your object you get a new object with copies of all primitive field (it is like deep copy) but also you have copy of all refernce fields. So in result you get two objects with they own copies of primitives and copies of references to the same objects - both original and copied object will use the same objects.

链接地址: http://www.djcxy.com/p/40798.html

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

下一篇: java中的clone()是浅拷贝吗?