[英]Store an array within a 2d array Java
So why doesn't this work? 那么为什么这不起作用呢? Not really sure why this isn't possible- I just want to store an array of size 2 inside a 2d array. 不确定为什么这是不可能的 - 我只是想在2d数组中存储一个大小为2的数组。
I know this would be equivalent to setting storage[0][0] = array[0] and storage[0][1] = array[1], but just wondering why this is incorrect. 我知道这相当于设置存储[0] [0] =数组[0]和存储[0] [1] =数组[1],但只是想知道为什么这是不正确的。
public class Test {
public static void main(String[] args) {
boolean[][] storage = new boolean[10][2];
boolean[] array = new boolean[2];
array[0] = true;
array[1] = false;
storage[0][] = array; //Why can't I do this?
}
}
Thanks in advance 提前致谢
You have a stray pair of brackets in your assignment. 你的作业中有一对偏离的括号。 Just use 只是用
storage[0] = array;
First of all boolean[][] storage = new boolean[10][2]
declares an array and initialise it. 首先boolean[][] storage = new boolean[10][2]
声明一个数组并初始化它。
So, you have created 11 arrays. 所以,你创建了11个数组。 One of boolean[]
element type and 10 of boolean type
. boolean[]
元素类型之一和boolean type
10。
It's good, If you want to access it's members directly, but if you create an inner array lately with new boolean[]
, it's an overhead. 这很好,如果你想直接访问它的成员,但是如果你最近使用new boolean[]
创建一个内部数组,那就是一个开销。
Use boolean[][] storage = new boolean[10][];
使用boolean[][] storage = new boolean[10][];
instead. 代替。
Then, you can access it's elements, which are boolean[]
type, and assign your array to it. 然后,您可以访问它的boolean[]
类型的元素,并将数组分配给它。
storage[0] = array;
Your problem is the stray square brackets(as I'm sure you know). 你的问题是流浪的方括号(我相信你知道)。 Your code should look like this: 您的代码应如下所示:
storage[0] = array;
The previous answers did not really explain why though, so that's what I'll do. 之前的答案并没有真正解释为什么,所以这就是我要做的。
What your trying to do is make the first position( storage[0]
) hold the same value as array
. 你要做的是让第一个位置( storage[0]
)保持与array
相同的值。 array
is 1 dimensional, so it can only be part of storage
, which is 2 dimensional. array
是1维的,因此它只能是storage
一部分 ,它是2维的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.