简体   繁体   English

在数组上克隆方法是深拷贝还是浅拷贝?

[英]Does clone method on array a deep or a shallow copy?

I'm not sure if the following will result in deep or shallow copy? 我不确定以下是否会导致深拷贝或浅拷贝?

public void viewImages(final String[] instancesFilename) {

    String[] instances = (String[])instancesFilename.clone();    
}

Is there a simple and fast way to deep copy a string array? 是否有一种简单而快速的方法来深度复制字符串数组?

Strings in Java are imutable(Can't change their value). Java中的字符串是可以改变的(不能改变它们的值)。 So there is no detectable difference between a deep and shallow copy when copying strings. 因此,在复制字符串时,深复制和浅复制之间没有可检测到的差异。

And just to further reference: The copy will be shallow but that should not be a problem since strings are imutable. 并且只是为了进一步参考:副本将是浅的,但这应该不是问题,因为字符串是可以改变的。

Oh and funny fact: Strings can't be cloned with the clone method, so if you try to do a deep copy of strings with the clone method, you will get a CloneNotSupportedException. 哦,有趣的事实:无法使用克隆方法克隆字符串,因此如果您尝试使用克隆方法执行字符串的深层复制,您将获得CloneNotSupportedException。

The array class also has the copyOf method. 数组类也有copyOf方法。 This is generally what I use for creating copies of arrays. 这通常是我用来创建数组副本的方法。 Heres and explanation of all of the differences: http://forum.codecall.net/topic/49450-copying-arrays/ 继承人和所有差异的解释: http//forum.codecall.net/topic/49450-copying-arrays/

Here is an interesting article discussing using serialization to make deep copies . 这是一篇有趣的文章,讨论使用序列化来制作深层副本

The objects in the call graph do need to support serialization however in many business types of 3 Tier applications, that necessity is there. 调用图中的对象确实需要支持序列化,但是在3层应用程序的许多业务类型中,必然存在这种情况。

The article provides a discussion of deep copy and shallow copy with some diagrams. 本文提供了深层复制和浅层复制的讨论,并附有一些图表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM