在同一行上声明多个 Java 数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4328339/
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
Declare Multiple Java Arrays on Same Line?
提问by Daniel Sopel
Is it possible to initialize and/or declare multiple arrays in the same line in Java?
是否可以在 Java 的同一行中初始化和/或声明多个数组?
ie.
IE。
int a, b, c, d, e = 4
works but
有效但
int[] a, b, c, d, e, = new int[4]
doesn't seem to work (size of array is 4)
似乎不起作用(数组大小为 4)
回答by Gwyn Evans
Bear in mind that
请记住
int a, b, c, d, e = 4;
is declaring 5 ints but only initialising 'e'.
正在声明 5 个整数,但只初始化“e”。
In the same way,
以同样的方式,
int[] a, b, c, d, e = new int[4];
will only initialise e.
只会初始化 e。
You'd need something like
你需要类似的东西
int[] a=new int[4], b=new int[4], etc...
which frankly, isn't worth one-lining...
坦率地说,这不值得单衬......
回答by Amir Raminfar
You are missing the new
keyword
Try this:
您缺少new
关键字试试这个:
int[] a, b, c, d, e = new int[4];
回答by redcayuga
try
尝试
int[] a = new int[4], b = new int[4], c = new int[4], d = new int[4], e = new int[4];
int[] a = new int[4], b = new int[4], c = new int[4], d = new int[4], e = new int[4];
You have to instantiate an array for each variable if you want to create five different arrays.
如果要创建五个不同的数组,则必须为每个变量实例化一个数组。
If you want to create one array and reference it from five variables Goran has the solution.
如果你想创建一个数组并从五个变量中引用它,Goran 有解决方案。
回答by Goran Jovic
What you tried is possible only for value types. In Java arrays are reference types i.e. objects.
您尝试的仅适用于值类型。在 Java 中数组是引用类型,即对象。
What you tried is not possible (as Gwyn explained).
您尝试的方法是不可能的(正如 Gwyn 所解释的)。
On the other hand you could:
另一方面,您可以:
int[][] arrays = new int[4][5];
And then use: arrays[0]
, arrays[1]
.. instead od a
,b
.
然后使用: arrays[0]
, arrays[1]
.. 而不是 od a
, b
.