如何在java中的for循环中创建数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22319669/
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-08-13 14:56:05  来源:igfitidea点击:

how to create array inside for loop in java

javaarrays

提问by Prasanth

I want to create 10 arrays inside a forloop, using the names 1, 2, 3, ..., 10 for the arrays.

我想在for循环中创建 10 个数组,使用名称 1, 2, 3, ..., 10 作为数组。

I tried like this, but it's not working:

我试过这样,但它不工作:

int n = 10;
for(int i = 0; i < n; i++)
{
    String [] i = new String[];
}

回答by Mc Kevin

you can't declare a variable with leading numbers.

您不能声明带有前导数字的变量。

回答by Scary Wombat

In you code iis already defined within the scope of the forloop. Also as soon as you exit the loop, the created variables will be out of scope.

在你的代码i中已经定义了for循环范围内。此外,一旦退出循环,创建的变量将超出范围。

Furthermore, variables beginning with an Integer are invalid in Java.

此外,以整数开头的变量在 Java 中无效。

回答by Kumar Abhinav

You should use a Mapto map number with array

您应该使用Map将数字与数组映射

Map<Integer,String[]> map = new HashMap<>(10);
for(int i=0; i < n; i++)
{
   map.put(i,new String[10]);
}

回答by Khaled.K

int n = 10;
int m = 5;

String[][] arrayOfArrays = new String[n][];

for(int i=0;i<n;i++)
{
    arrayOfArrays[i] = new String[m];
}

回答by MjZac

You can use ArrayListfor creating an array of array, else go for a 2D Stringarray.

您可以ArrayList用于创建数组数组,否则请使用二维String数组。

ArrayList<String[]> x = new ArrayList<String[]>();
    int n =10;
    for(int i=0;i<n;i++){
        x.add(new String[5]);
    }

回答by Sky

you might want to use a 2D array which might offers what you need.

您可能想要使用可能提供您需要的二维数组。

Read this Syntax for creating a two-dimensional array

阅读此语法以创建二维数组

String [][] test = new String [10][10];

It is as if the first [] can be your 'i' like what you required, and the 2nd [] can be what you need to store the variable. It is normally use for cases like if you need an "array of array", meaning 100x array.

就好像第一个 [] 可以是你的“i”,就像你需要的一样,第二个 [] 可以是你需要存储变量的东西。它通常用于诸如需要“数组数组”之类的情况,这意味着 100x 数组。