Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error when copying an array to another in Java

Tags:

java

arrays

copy

After googling for a while, I'm aware that there quite a few ways to copy an array to another in Java, namely using System.arraycopy.

However a few of my friends tried to use this:

boolean a[][] = new boolean[90][90];
boolean b[][] = new boolean[90][90];

/* after some computations */

a = b

This produces a rather non deterministic result, does anyone know what this actually does?

like image 417
Enrico Susatyo Avatar asked Jul 24 '26 12:07

Enrico Susatyo


1 Answers

It's not non-deterministic at all.

a = b;

simply assigns the value of b to a. The value of b is a reference to the array - so now both variables contain references to the same array. The old value of a is irrelevant - and if it referred to an array which nothing else referred to, it will now be eligible for garbage collection.

Note that this isn't specific to arrays - it's the way all reference types work in Java.

Basically, you're not copying one array into another at all - you're copying the reference to an array into another variable. That's all.

like image 103
Jon Skeet Avatar answered Jul 27 '26 02:07

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!