java 如何初始化未知数组长度的多维数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6176627/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 14:41:59  来源:igfitidea点击:

How to initialize a multi-dimensional array of unknown array length

javaandroid

提问by Kumar Anil

I am getting problems when generating a multi-dimensional array with unknown size. How can I fix it?

生成大小未知的多维数组时遇到问题。我该如何解决?

回答by RMT

To generate a multi-dimensional array with unknown size is called a jagged array.

生成大小未知的多维数组称为锯齿数组。

For example:

例如:

String[][] array = new String[5][];

Java uses arrays of arrays for multi-dimensional arrays. I think you have to specify the first size. Otherwise, use list of lists.

Java 将数组的数组用于多维数组。我认为您必须指定第一个尺寸。否则,使用列表列表。

ArrayList<ArrayList<String>> list = new ArrayList<ArrayList<String>>();

回答by Sunil Kumar Sahoo

Array is static. ArrayList is dynamic.

数组是静态的。ArrayList 是动态的。

Before creating an array you should be aware of the size of the array. To create a multidimensional array without knowing array size is not possible.

在创建数组之前,您应该了解数组的大小。在不知道数组大小的情况下创建多维数组是不可能的。

Better you have to use a nested ArrayListor nested Vector:

最好使用嵌套ArrayList或嵌套Vector

ArrayList<ArrayList<String>> list = new ArrayList<ArrayList<String>>();

回答by Haphazard

You can either use a List of Lists or just declare the array to as big as you expect it to ever get.

您可以使用列表列表,也可以将数组声明为您期望的大小。