Java 静态数组

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

Java-static arrays

java

提问by Ruba

i have a class called (User) and i want to make a multidimensional array of it i have wrote

我有一个名为 (User) 的类,我想为其编写一个多维数组

static User [][] userlist=new User[6][];

and i have a compiler error that is : illegal start of expression

我有一个编译器错误:非法的表达式开始

thanks a lot .

多谢 。

采纳答案by Mark Peters

Here's an example of a 5x5 2-dimensional array:

下面是一个 5x5 二维数组的例子:

private static int[][] matrix = new int[5][5];

//set index 1, 2 to 5
matrix[1][2] = 5;

The static part really makes no difference; just declare the member as static.

静态部分真的没有区别;只需将成员声明为静态。

回答by Jigar Joshi

static int[][] arr = new int[2][4] ;
arr[0][0]=1;
arr[0][1]=2;
.
.
arr[0][3]=4;

回答by Peter Lawrey

Similar to @Mark solution, you can initialise a multi-dimensional array

类似于@Mark的解决方案,可以初始化一个多维数组

private static int[][] matrix = {
    { 1,2,3,4,5 },
    { 6,7,8,9,10 }
};

回答by Peter Lawrey

There are a number of nice answers, so this is more informative than anything:

有很多不错的答案,所以这比任何事情都提供更多信息:

The problem is that all dimensions mustbe specified explicitly or implicitly -- and the new X[..][..][..]etc, (explicitly specified dimensions) form requires that each dimension (..) is a (non-negative) integer expression. The javac compiler is throwing that error because it found the last ]but was expecting an integer expression.

问题是必须显式或隐式指定所有维度——new X[..][..][..]等(显式指定维度)形式要求每个维度 ( ..) 是(非负)整数表达式。javac 编译器抛出该错误,因为它找到了最后一个]但期望一个整数表达式。

new User[6][/*you need an integer expression here*/];

Happy coding.

快乐编码。