Java 整数数组静态初始化
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4449935/
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
integer array static initialization
提问by user516108
Which two code fragments correctly create and initialize a static array of int elements? (Choose two.)
哪两个代码片段正确地创建和初始化了一个 int 元素的静态数组?(选择两项。)
A.
一种。
static final int[] a = { 100,200 };
B.
B.
static final int[] a;
static { a=new int[2]; a[0]=100; a[1]=200; }
C.
C。
static final int[] a = new int[2]{ 100,200 };
D.
D.
static final int[] a;
static void init() { a = new int[3]; a[0]=100; a[1]=200; }
Answer: A, B
答案:A、B
here even D seems true, can anyone let me know why D is false.
这里甚至 D 似乎是真的,谁能告诉我为什么 D 是假的。
采纳答案by buc
The correct answers are 1 and 2 (or A and B with your notation), and an also correct solution would be:
正确答案是 1 和 2(或带有符号的 A 和 B),一个同样正确的解决方案是:
static final int[] a = new int[]{ 100,200 };
Solution D doesn't initalize the array automatically, as the class gets loaded by the runtime. It just defines a static method (init), which you have to call before using the array field.
解决方案 D 不会自动初始化数组,因为该类是由运行时加载的。它只是定义了一个静态方法 (init),您必须在使用数组字段之前调用它。
回答by Cameron Skinner
D defines a static method for initialising a
but does not actually call it. Thus, a
remains uninitialised unless someone explicitly calls the init
method.
D 定义了一个用于初始化的静态方法,a
但实际上并没有调用它。因此,a
除非有人明确调用该init
方法,否则将保持未初始化状态。
As other answers have pointed out: D shouldn't even compile because it attempts to assign a value to the final
variable a
. I guess that's a much more correct explanation. Nevertheless, even if a
was not final D would still not work without extra code.
正如其他答案所指出的那样: D 甚至不应该编译,因为它试图为final
变量分配一个值a
。我想这是一个更正确的解释。尽管如此,即使a
不是最终的 D 仍然无法在没有额外代码的情况下工作。
I assume the new int[3]
in D is a typo? The other three all attempt to create an array of length 2.
我认为new int[3]
在 D 是一个错字?其他三个都试图创建一个长度为 2 的数组。
回答by khachik
D (4) is false, because a) a
is final and you cannot assign it in init
; b) there is no guarantee that init
will be called; c) init
doesn't set the third element;
D (4) 是错误的,因为 a)a
是最终的,您不能将其赋值给init
; b) 不保证init
会被调用;c)init
不设置第三个元素;
回答by Ratna Dinakar
for snippet C You cannot give dimensions ( Size ) while initializing for snippet D you should initialize final variable. It cannot be initialized later.
对于片段 C 在初始化片段 D 时您不能给出尺寸( Size ),您应该初始化最终变量。以后不能初始化。
回答by Ajay Sharma
final variables should be initialized before constructor call completes. Since "static void init()" is a method & it will not run before constructor, final variables won't be initialized. Hence it is an compile time error.
final 变量应该在构造函数调用完成之前初始化。由于“static void init()”是一种方法,它不会在构造函数之前运行,因此不会初始化最终变量。因此,这是一个编译时错误。