I did the task but i tried to copy the passed array using Arrays.copyOf(a, a.length). This did copy it but also it was mirroring my alternations to the original.
So i had to copy oldschool with a for loops....
Shouldn't .copyOf() create a distinct copy of the given array that is not affecting the original? Or is there a better way to get there anyways?
I can provide the code if needed.
thaks!
"Arrays.copyOf(original, newLength)" works wierd?
Resolved
Comments (2)
- Popular
- New
- Old
You must be signed in to leave a comment
Nouser
18 February 2021, 12:50solution
copyOf creates a shallow copy of an array. Means if you hava an array of primitives it gets copied without any problem. If you have an array of objects, then it copies the reference variables. So both arrays refer to the same objects. A two dimensional array of primitives in the end is an array containing arrays. So you copy reference variables to arrays. Again both arrays reference the same objects.
You could try to use clone() or the streams api, but these also do shallow copying. In the end you will always nest loops and take care of the copying yourself. With streams you could call clone two times one behind the other, first for the 1st and then for the 2nd dimension. That may work. Still it is nothing else than a nested loop and no solution out of the box.
+2
MoJo
19 February 2021, 11:46
Very informative, thanks!
0