gpt4 book ai didi

scala - Scala AnyRef.clone 执行浅复制还是深复制?

转载 作者:行者123 更新时间:2023-12-02 05:18:10 25 4
gpt4 key购买 nike

在 Scala 中,AnyRef.clone 执行浅复制还是深复制?

最佳答案

简短回答:浅薄。

不太简短的答案:除非被重写,否则 AnyRef.clone() 使用 Java 的 Object.clone() 作为其实现。

关于 Object.clone() 的 Javadoc:

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.

请注意:

  1. AnyRef.clone() 与 Java 中的对应项一样,具有“ protected ”访问级别,因此它无法从任何地方调用。
  2. 您需要实现 Cloneable 才能使 clone() 正常工作。

长答案:阅读《Effective Java》,第二版,第 11 条:明智地覆盖克隆

摘要:不要使用它。有更好的选择。

关于scala - Scala AnyRef.clone 执行浅复制还是深复制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1267261/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com