简体   繁体   English

基本深层复制,Java

[英]Basic Deep Copy, Java

Okay, so i know there is a million questions out there on deep copy but i still have a hard time understanding because there is all this talk about cloning and serialization and what not. 好的,所以我知道在深层副本上还有一百万个问题,但是我仍然很难理解,因为所有这些都涉及克隆和序列化,而并非如此。 When making a deep copy of a String[] array is this how you would do it in a very simple way? 制作String []数组的深层副本时,这是如何以一种非常简单的方式进行? without validating. 未经验证。

public String[] copyString(String[] others)
  {
    String[] copy = new String[others.length];
    for (int i = 0; i < others.length; i++)
    {
      copy[i] = others[i];
    }

    return copy;
  }

When making a deep copy of a String[] array is this how you would do it in a very simple way? 制作String []数组的深层副本时,这是如何以一种非常简单的方式进行?

Yes. 是。

You need to 你需要

  1. allocate a new object 分配一个新对象
  2. deep-copy the contents from the source object 深度复制源对象中的内容

and that's exactly what your method does. 这正是您的方法所要做的。

Note that this only works because String is immutable, otherwise you would be performing a shallow copy of the contents. 请注意,这仅适用于String是不可变的,否则您将执行内容的浅表复制。

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

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