简体   繁体   English

可以在Java中改变N维数组的大小吗?

[英]Can the size of an N-dimensional array change in Java?

An array in Java is an object. Java中的数组是一个对象。 So if I have a 2D array double[][] matrix = new double[5][5] then each row of that array is an object referencing a single dimensional array in memory. 因此,如果我有一个2D数组double[][] matrix = new double[5][5]那么该数组的每一行都是一个引用内存中单维数组的对象。 From my understanding, once the array size is set in java it can not be changed. 根据我的理解,一旦在java中设置了数组大小,就无法更改。 So let me declare a 1D array double[] d = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} I am then allowed to set matrix[1] = d so that row 1 is now pointing to d in memory. 所以让我声明一个1D数组double[] d = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}然后我可以设置matrix[1] = d这样第1行就是现在指向内存中的d。 I seems like the array size is not really fixed. 我似乎没有真正修复数组大小。 I can declare matrix to be of any size and just change the reference to point to an array of a different size. 我可以将matrix声明为任意大小,只需将引用更改为指向不同大小的数组。 Why am I allowed to do this if the matrix size is fixed to be 5 x 5 ? 如果matrix大小固定为5 x 5,为什么我可以这样做?

The assignment 分配

double[][] matrix = new double[5][5];

actually creates 6 array objects. 实际上创建了6个数组对象 One array whose element type is double[] (ie an array of double arrays) having a length of 5 and referenced by the matrix variable, and 5 arrays whose element types are double having a length of 5 and references by matrix[0]...matrix[4] . 一个数组类型为double[]的数组(即双数组数组),长度为5,由matrix变量引用,5个数组的元素类型为double ,长度为5,由matrix[0]...matrix[4]引用matrix[0]...matrix[4]

Just as you can change the matrix variable to refer to a new array by assigning : 就像你可以通过赋值改变matrix变量来引用一个新数组一样:

matrix = new double[10][10];

you can also change any of the references matrix[i] to refer to a new array by assigning : 您还可以通过指定以下内容来更改任何引用matrix[i]以引用新数组:

matrix[i] = new double[6];

You are not changing any existing array. 您没有更改任何现有阵列。 You are changing the value of a reference variable which referred to one array to refer to a different array. 您正在更改引用变量的值,该引用变量引用一个数组以引用不同的数组。

Simply spoken: because that is how the fathers of Java made arrays work. 简单地说:因为这就是Java的父亲使阵列工作的方式。

And the syntax gives a hint there: 语法给出了一个提示:

double[][] matrix = new double[5][5]

You see, the 5,5 only shows up on the right hand side ! 你看,5,5只出现在右手边 Meaning: the array dimensions are not part of "type" of matrix ! 含义:数组维度不是 矩阵 “类型”的一部分!

The key thing is: there are no true "multi dimensional" arrays in Java. 关键是:Java中没有真正的“多维”数组。 There is no way to say: this thing should be "5 x 5". 没有办法说:这个东西应该是“5 x 5”。 You always end up with an array of "rows"; 你总是得到一排“行”; and each row contains an array of columns. 每行包含一列列。 And therefore, those columns can have different lengths,as they are completely independent of each other! 因此,这些列可以具有不同的长度,因为它们完全相互独立!

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

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