Back to Browse

Program 11 Array reference program | Shallow copy | Deep copy | Array slice | ...operator

62 views
Apr 7, 2023
3:21

In this program, we create an array arr with the values [1, 2, 3, 4, 5]. Then, we create a new variable tempArr and assign it the same reference to the array as arr (i.e., they both refer to the same array in memory). Next, we modify the value of the element at index 2 of tempArr to be 100. Since tempArr and arr both refer to the same array, this also modifies the value of the element at index 2 of arr. When we log arr and tempArr to the console, we see that both arrays have the same modified values: [1, 2, 100, 4, 5]. This is because they both refer to the same array in memory, so any changes made to one array are reflected in the other. shallow copy:- --------------- shallow copy, also known as a "shallow clone," is a type of copying process in which a new object is created that points to the same memory location as the original object. In other words, a shallow copy does not create a new copy of the original data; instead, it creates a new reference to the same data as the original object. Any changes made to the shallow copy will affect the original object, and vice versa. This can be contrasted with a deep copy, which creates a new object that is a completely separate copy of the original object, with its own memory location and data. Shallow copying can be useful when you want to create a new object that refers to the same data as an existing object, but with some slight modifications. However, it can also be dangerous if you're not aware that changes to one object will affect the other object as well. Deep copy:- --------------- Deep copy, also known as a "deep clone," is a type of copying process in which a new object is created that is a complete and separate copy of the original object. In other words, a deep copy creates a new object with its own memory location and data, and any changes made to the new object will not affect the original object, and vice versa. This can be contrasted with a shallow copy, which creates a new object that points to the same memory location as the original object, so any changes made to the shallow copy will affect the original object. Deep copying can be useful when you want to create a new object that is independent of the original object, and any changes made to the new object will not affect the original object. However, deep copying can also be more time and memory-consuming than shallow copying, especially for large objects or data structures.

Download

0 formats

No download links available.

Program 11 Array reference program | Shallow copy | Deep copy | Array slice | ...operator | NatokHD