Scala AnyRef.clone是否执行浅拷贝或深拷贝? [英] Does Scala AnyRef.clone perform a shallow or deep copy?
问题描述
在Scala中, AnyRef.clone
执行浅拷贝还是深拷贝?
In Scala, does AnyRef.clone
perform a shallow or deep copy?
推荐答案
简短答案:简短。
不太简短的答案:
除非被覆盖,否则AnyRef.clone()将使用Java的Object.clone()作为其实现。
Not-so-short answer: Unless it's overridden, AnyRef.clone() uses the Java's Object.clone() as its implementation.
Object.clone()上的Javadoc:
Javadoc on Object.clone():
类Object
的方法克隆执行特定的克隆操作。
首先,如果此对象
的类未实现
Cloneable接口,则抛出
CloneNotSupportedException。
注意,所有数组都被视为
实施接口Cloneable。
否则,此方法将创建此对象
的类的新
实例,并使用
初始化其所有字段,而该字段恰好与此对象的
对应字段的内容相同,
,好像是通过分配;
的内容本身不会被克隆。
因此,此方法对该对象执行浅
复制操作,而不是深
复制操作。
The method clone for class Object performs a specific cloning operation. First, if the class of this object does not implement the interface Cloneable, then a CloneNotSupportedException is thrown. Note that all arrays are considered to implement the interface Cloneable. Otherwise, this method creates a new instance of the class of this object and initializes all its fields with exactly the contents of the corresponding fields of this object, as if by assignment; the contents of the fields are not themselves cloned. Thus, this method performs a "shallow copy" of this object, not a "deep copy" operation.
请注意:
- AnyRef.clone()与Java中的对应文件一样,具有受保护访问级别,因此它的不能可以在任何地方调用。
- 您需要实现Cloneable才能使clone()正常工作。
- AnyRef.clone(), like its counterpart in Java, has a "protected" access level, so its not callable from everywhere.
- You will need to implement Cloneable in order for clone() to work.
长答案:阅读 Effective Java,第二版,第11项:明智地覆盖克隆
摘要:请勿使用。还有更好的选择。
Summary: Don't use it. There are better alternatives.
这篇关于Scala AnyRef.clone是否执行浅拷贝或深拷贝?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!