After googling for a while, I'm aware t开发者_JAVA百科hat 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?
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.
Lines of Code and their meanings:
boolean a[][] = new boolean[90][90];
Allocate an array and assign its reference to a
boolean b[][] = new boolean[90][90];
Allocate a second array and assign its reference to b
a = b;
Assign bs value (second arrays reference) to a.
Before a=b;
a ---------> First arrays memory space
b ---------> Second arrays memory space
After a=b;
a --- First arrays memory space
---
------>
b ------------> Second arrays memory space
Now you lost first array forever
Remember a=b means you are assigning value of b to a
boolean a[][] = new boolean[90][90];
boolean b[][] = new boolean[90][90];
a[0][3]=false;
b=a;
a[0][5]=true;
System.out.println(b[0][3]);
System.out.println(b[0][5]);
The output is:-
false
true
精彩评论