简体   繁体   English

这会是深层复制的一个例子吗?

[英]would this be an example of deep copy?

int[] a = new int[10];
for (int i = 0; i < 10; i++) {
    a[i] = randomFill();//randomFill is a method that generates random numbers
}

int[] b = new int[a.length];
for (int j = 0; j < a.length; j++) {
    b[j] = a[j]
}

int[] c = new int[a.length];
for(int k = 0; k < a.length; k++) {
    c[k] = a[k]
}

are both array b and array c the deep copy of array a? 数组b和数组c都是数组a的深层副本吗? I need to modify array a but want to keep its original values so that I can use it for later and the hint I received was to use deep copy. 我需要修改数组a,但希望保留其原始值,以便我可以在以后使用它,我收到的提示是使用深层复制。 I can't tell if my code is considered as deep copy ... 我不知道我的代码是否被视为深拷贝...

a is an array of int (s), they only have a primitive value - so the answer is yes. a是一个int (s)数组,它们只有一个原始值 - 所以答案是肯定的。 Modifying b (or c ) will not affect a . 修改b (或c )不会影响a But, you could use Arrays.copyOf(int[], int) like 但是,您可以使用Arrays.copyOf(int[], int)类的

int[] b = Arrays.copyOf(a, a.length);
int[] c = Arrays.copyOf(a, a.length);

Deep copy term couldn't be applied to copying plain array of integers. Deep copy术语不能应用于复制纯整数数组。 This is about more complex data structures like collections of objects which can also contain nested objects/collections. 这是关于更复杂的数据结构,如对象集合,也可以包含嵌套对象/集合。

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

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