用Java初始化多维数组 [英] Initialising a multidimensional array in Java

查看:42
本文介绍了用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] 将失败,因为索引 xy 超出范围.

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初始化多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆