john lee
john lee

Reputation: 55

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? 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. I can't tell if my code is considered as deep copy ...

Upvotes: 4

Views: 68

Answers (2)

Volodymyr Kostin
Volodymyr Kostin

Reputation: 79

Deep copy term couldn't be applied to copying plain array of integers. This is about more complex data structures like collections of objects which can also contain nested objects/collections.

Upvotes: 1

Elliott Frisch
Elliott Frisch

Reputation: 201477

a is an array of int(s), they only have a primitive value - so the answer is yes. Modifying b (or c) will not affect a. But, you could use Arrays.copyOf(int[], int) like

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

Upvotes: 3

Related Questions