在Java中初始化多维数组

在Java中初始化多维数组

本文介绍了在Java中初始化多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

声明多维数组并为其赋值的正确方法是什么?

What is the correct way to declare a multidimensional array and assign values to it?

这就是我所拥有的:

int x = 5;
int y = 5;

String[][] myStringArray = new String [x][y];

myStringArray[0][x] = "a string";
myStringArray[0][y] = "another string";


推荐答案

尝试用以下代码替换相应的行:

Try replacing the appropriate lines with:

myStringArray[0][x-1] = "a string";
myStringArray[0][y-1] = "another string";

您的代码不正确,因为子数组的长度为 y ,索引从0开始。因此设置为 myStringArray [0] [y] myStringArray [0] [x] 将失败,因为索引 x y 超出界限。

Your code is incorrect because the sub-arrays have a length of y, and indexing starts at 0. So setting to myStringArray[0][y] or myStringArray[0][x] will fail because the indices x and y are out of bounds.

String [] [] myStringArray = new String [x] [y]; 是初始化矩形多维数组的正确方法。如果你希望它是锯齿状的(每个子数组可能有不同的长度),那么你可以使用类似于。但请注意,在您需要完全矩形的多维数组的情况下,John必须手动创建子数组的断言是不正确的。

String[][] myStringArray = new String [x][y]; is the correct way to initialise a rectangular multidimensional array. If you want it to be jagged (each sub-array potentially has a different length) then you can use code similar to this answer. Note however that John's assertion that you have to create the sub-arrays manually is incorrect in the case where you want a perfectly rectangular multidimensional array.

这篇关于在Java中初始化多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 20:06