boolean[][] values = new boolean[3][4];
System.out.println(values.length);
values[2] = new boolean[8];
System.out.println(values[2].length + " " + values[0].length);
This is a multiple choice question that I'm having trouble with. The answer is supposed to be:
3
8 4
but I thought that an array's size cannot be changed once it is created. Any explanations would be much appreciated.
You are not changing the length of an array, you are creating a new one of a different length.
values[2] = new boolean[4];
assert values[2].length == 4;
values[2] = new boolean[8];
assert values[2].length == 8;
is just like writing
boolean[] values2 = new boolean[4];
assert values2.length == 4;
values2 = new boolean[8];
assert values2.length == 8;
Note: a boolean[]
variable is a reference to an array. It is not the array object so when you change this reference you point to a different object.
values = new boolean[3][4]
... creates an array of length 3, pointed to by a variable called values
. Each of the three elements in values
points to an array of length 4.
So:
System.out.println(values.length);
... prints 3.
values[2] = new boolean[8];
... creates a new array of length 8, and makes element 2 of values
point to it.
The array that used to be element 2 of values no longer has a reference -- it's lost (if the JVM stays around long enough, it will be cleared away by garbage collection).
values[0]
is still the 4 element array created at the start. values[2]
is the newly created array of length 8.
In Java, two-dimensional arrays are actually arrays of arrays, not a block of bytes that's divided into rows, as it is in some other languages.
When you declare an array as
boolean[][] values = new boolean[3][4];
It's basically just a shorthand to writing:
boolean[][] values = {
new boolean[4],
new boolean[4],
new boolean[4]
};
So you have an array whose elements are arrays of booleans.
There is nothing stopping you from changing one of the entries in this array. You have a first array, a second array, and a third array, and you are just replacing the third.
Thus, it is not changing the size of the array, because the declaration new boolean[3][4]
only sets a fixed size for the first dimension, and for the initial values (arrays) in it. But you can replace those initial values with new values which have a different size if you wish - as long as you don't try to change the size of the main array.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.