简体   繁体   English

为什么在创建一维数组对象时需要定义数组长度?

[英]Why do we need to define array length when creating one-dimensional arrays object?

for example: why this statement long[] n= new long[]; 例如:为什么这句话long[] n= new long[]; is wrong but this statement long[][] n= new long[1][]; 是错的,但这句话long[][] n= new long[1][]; is right? 是正确的? How does the memory know how much memory needs to be assigned to the object in the second statement? 内存如何知道在第二个语句中需要为对象分配多少内存?

How does the memory know how much memory needs to be assigned to the object in the second statement? 内存如何知道在第二个语句中需要为对象分配多少内存?

Two things to remember here to figure out what's going on: 要记住两件事要弄清楚发生了什么:

  • 2D Java arrays aren't square, they're arrays of arrays. 2D Java数组不是正方形,它们是数组的数组。
  • You specify the size of an array when it's created. 您可以在创建数组时指定数组的大小。

So in this example, you're creating an array of longs (of size 1) to hold another array of longs - but you're not yet creating the second array (so you don't need to specify how large it will be.) In effect, the first array provides an empty "slot" (or slots if the outer array is longer than 1) for the inner array(s) to sit in - but the inner array(s) haven't yet been created, so their size doesn't need to be specified. 所以在这个例子中,你创建了一个longs数组(大小为1)来保存另一个long数组 - 但是你还没有创建第二个数组(所以你不需要指定它的大小。 )实际上,第一个数组提供了一个空的“槽”(如果外部数组长于1,则为槽),内部数组可以放入 - 但内部数组尚未创建,所以不需要指定它们的大小。

It doesn't just create an array of arbitrary length at all, it simply doesn't create any inner arrays. 它不仅仅创建一个任意长度的数组,它根本不会创建任何内部数组。

You can perhaps see this more clearly if you try to access or store a long in the 2D array: 如果您尝试在2D数组中访问或存储long,则可以更清楚地看到这一点:

long[][] x = new long[2][];
x[0][0] = 7;

...will produce a NullPointerException (on the second line), because there is no inner array there to access. ...将产生NullPointerException (在第二行),因为没有内部数组可供访问。

In the first example that doesn't compile, you're trying to actually create an array of longs, but not giving it a dimension, hence the error. 在第一个没有编译的例子中,你试图实际创建一个long数组,但不给它一个维度,因此错误。

when you write this - long[][] n= new long[1][]; 当你写这个 - long[][] n= new long[1][];

you are creating array of arrays of long but you are not actually initializing those arrays right now 你正在创建long 数组但你现在实际上并没有初始化这些数组

So if you do n[0] == null it will return true 因此,如果你执行n[0] == null ,它将返回true

that way you are free to initialize new array in any point of time later- 这样你可以在以后的任何时间点自由地初始化新阵列 -

n[0] = new long[10];

So the point is - you need to provide size while initializing your array , that is why long[] n= new long[]; 所以关键是 - 你需要在初始化数组时提供大小,这就是为什么long[] n= new long[]; is wrong 是错的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM