在java浅拷贝中是clone()吗? [英] Is clone() in java shallow copy?

查看:148
本文介绍了在java浅拷贝中是clone()吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

java中的 clone()浅层副本?

Is clone() in java a shallow copy?


最终这个获取对象的clone()
方法(最上面的
类),它创建一个与对象相同的类的新实例

将所有字段复制到新的
实例(浅拷贝)。

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").

我从维基百科

我不明白为什么它是浅层副本。 clone()将创建一个包含所有字段的新实例。这只是一个很深的副本吗?困惑。需要一些解释。

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.

推荐答案

默认 Object.clone()确实是一个浅薄的副本。但是,它被设计为抛出 CloneNotSupportedException ,除非您的对象实现 Cloneable

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

当你实现 Cloneable 时,你应该覆盖 clone()通过在所有可复制的字段上调用 clone()来使其执行深层复制。

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.

这篇关于在java浅拷贝中是clone()吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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