How to Make a Shallow Copy of an Array

How to make a shallow copy of an array?

You can clone an array, which makes a copy of it:

int[,] originalValues = (int[,])this.Metrics.Clone();

How can I create a shallow copy of an array with a map like function?

You cannot make a "shallow copy" of primitive values - when you make arr.map(tile => tile[3]) you are making a new array with new values, so changing one doesn't change the other.

However, you can make an array of objects, as the values of objects are their references

let grid = [  [{value: 1}, {value: 2}],  [{value: 3}, {value: 4}],];
//take a columnlet col2 = grid.map(row => row[1]);
//change one valuecol2[1].value = 42;
//the original changedconsole.log(grid);

(Array.Clone) Shallow Copy vs Deep Copy of an Array

A Shallow Copy of an Array is not the same as a copy of an array:

  • Copying an array, copies the reference to the array to a new variable. Both variables will be pointing to the same values.
  • The Clone method creates a new, distinct array containing a copy of the elements of the original array. If those elements are value types (like in your case ìnt) the new array will contain the same set of values as the original but stored in another location.

    If the elements of the array are of a reference type, the new array will contain copies of the original references. So the first elements of both array would contain the same reference to an object.

See also: https://learn.microsoft.com/en-us/dotnet/api/system.array.clone?view=net-6.0

A shallow copy of an Array copies only the elements of the Array, whether they are reference types or value types, but it does not copy the objects that the references refer to. The references in the new Array point to the same objects that the references in the original Array point to.

How to make a shallow copy of an array and store that copy in a struct

Shallow copy amounts to copying the references instead of the values. However, this requires defining the struct a bit differently:

typedef struct Heap {
int length;
int size;
int *A;
} Heap;

This way, the values of the array A are not contained immediately after the struct, and we have the freedom to assign any pointer to it. Then, we simply init the heap as:

Heap * build_max_heap(int A[], int length) {
Heap * heap = malloc(sizeof(Heap));
*heap = (Heap) { length, length, A };
/* ... heapify code etc ... */
return heap;
}

But you must use this with caution - this implies that if you create two heaps out of A, they will influence each other. It is still best practice to create a copy.

How to make shallow copy of array in swift

Arrays are value types. When we copy them, each copy is independent of the other. This is a virtue in Swift. What you are trying to do requires references so that effects on one can be seen by others. Try this code. Create a class (reference type) containing your data. Now changes to the container can be seen in the other.

class Person
{
var name: String

init(_ name: String) {
self.name = name
}
}

let p1 = Person("Umair")
let p2 = Person("Ali")

class Container {
var people = [Person]()

init(people: [Person]) {
self.people = people
}
}

let arr1 = Container(people: [p1, p2])
let arr2 = arr1

print(arr1.people)
print(arr2.people)

arr1.people.removeFirst()

print(arr1.people)
print(arr2.people)

Sample Image

Java - Implement deep and shallow copy of an array

I am trying to understand the concept of shallow vs deep copy in Java.

In Java you pass around and store references to objects not the objects themselves.

So when you have an NameValue[] array the array does not contain the objects NameValue but references to the objects.

So when you do a shallow copy to NameValue[] array2 it means you are just copying the references from one array to the other. Which effectively means that now both array and array2 refer to exactly the same objects and any change you do from array[2] will be visible from array2[2] (same object).

When you deep copies you copy each object completely to another memory area and you keep a reference to that new object in your new array.

This way the 2 arrays now refer to different objects and any change to array[2] are not visible from array2[2]

Update:
This does not apply to primitives that do store the actual value and not a reference.

So an int[] a when you copy you get a copy of the values (i.e. deep copy in a sense) because a[2] contains the value itself and not the reference to the value.

Selective shallow copy from one array to another

You will need an array of integer pointers for that.

int *arr2[5];

for (int i = 0, j = 0; i < 10; i++) {
if (!(i%2)) {
arr2[j]= &arr[i];
j++;
}
}

So you need to set each element of arr2 to point to corresponding element in arr by arr2[j]= &arr[i];

When you need to access element in arr2, you call some thing like: int a = *arr2[j];

Later on let say you change arr[0] to 10 arr[0] = 10; then int a = *arr2[0]; will give you 10.

Fastest way to duplicate an array in JavaScript - slice vs. 'for' loop

There are at least 6 (!) ways to clone an array:

  • loop
  • slice
  • Array.from()
  • concat
  • spread operator (FASTEST)
  • map A.map(function(e){return e;});

There has been a huuuge BENCHMARKS thread, providing following information:

  • for blink browsers slice() is the fastest method, concat() is a bit slower, and while loop is 2.4x slower.

  • for other browsers while loop is the fastest method, since those browsers don't have internal optimizations for slice and concat.

This remains true in Jul 2016.

Below are simple scripts that you can copy-paste into your browser's console and run several times to see the picture. They output milliseconds, lower is better.

while loop

n = 1000*1000;
start = + new Date();
a = Array(n);
b = Array(n);
i = a.length;
while(i--) b[i] = a[i];
console.log(new Date() - start);

slice

n = 1000*1000;
start = + new Date();
a = Array(n);
b = a.slice();
console.log(new Date() - start);

Please note that these methods will clone the Array object itself, array contents however are copied by reference and are not deep cloned.

origAr == clonedArr //returns false
origAr[0] == clonedArr[0] //returns true


Related Topics



Leave a reply



Submit