What is the simplest way to set one array equal to another without linking them

say I have:

int[] a = {10, 10};
int[] b = {0, 0};

what is the simplest way to set b = a without making the variables linked. (changing a value in a will change a value in b);

do I have to use a for loop?

p.s. in the actual project this is for the arrays are also several layers deep.

1 Like
int[] a = { 10, 10 };
int[] b = a.clone();
3 Likes

Putting .clone(), which is mentioned by GoToLoop, gives an identical unrelated clone of any object you use it on.

The reason this happens is because of how Java objects work. An array is an object, and a variable only contains a pointer in memory to that object.
When you do b = a, you are setting b to the same pointer that a has. As a result, they both point to the same object, so doing operations on any of them would do the operation on an object that they both point to. “Object” here being an integer array.

Almost anything in Java(and Processing since it uses Java) is an object. Even String is. However, there is no need to do .clone() on a string because, as I understand, any operations on strings result in a new unrelated object being made each time.

Then there’s Java’s garbage collector system - when you, for example, do a = null, or otherwise get rid of all pointers to an object, i.e. leave it completely inaccessible, Java clears it from the RAM automatically sooner or later.

a = null means setting a to a null pointer, which is literally pointing to nothingness. Keep in mind that any operations on a when it’s set to null will result in a nullPointerException error.
However, if you feel like optimizing your code to use less RAM, it doesn’t hurt to have a habit of setting objects and stuff to null once you don’t need it.

Also, when you will be making your own classes(i.e. definitions of objects), keep in mind that if you store other objects inside of yours, .clone() function will copy over the pointers to these objects, potentially making a mess of objects housing objects that are same between those first objects, and, yeah. You’d want to make a “deep copy” in that case - which would involve making deepcopy() function in an object that calls deepcopy() inside of all objects that it contains, to make a fully unrelated copy…

Multi-dimensional arrays (i.e. int[][]) are literally arrays of arrays, i.e. objects containing more objects, so you should think about this when cloning a multi-dimensional array, and figure a deep copy of such too.

This OOP (Object Oriented Programming) stuff can be a bit of a hassle to understand, but can be really useful if you get it!

…I digressed here a little, if you don’t mind. ._.

3 Likes