简体   繁体   English

整数数组静态初始化

[英]integer array static initialization

Which two code fragments correctly create and initialize a static array of int elements? 哪两个代码片段正确创建并初始化int元素的静态数组? (Choose two.) (选择两个。)

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是假的。

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. 解决方案D不会自动初始化数组,因为运行时会加载类。 It just defines a static method (init), which you have to call before using the array field. 它只定义了一个静态方法(init),在使用数组字段之前必须调用它。

D defines a static method for initialising a but does not actually call it. D定义了一个静态方法来初始化a但实际上并没有调用它。 Thus, a remains uninitialised unless someone explicitly calls the init method. 因此, 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 . 正如其他答案所指出的那样:D甚至不应该编译,因为它试图为final变量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. 然而,即使a没有最终d仍然没有额外的代码工作。

I assume the new int[3] in D is a typo? 我假设D中的new int[3]是拼写错误? The other three all attempt to create an array of length 2. 其他三个都试图创建一个长度为2的数组。

D (4) is false, because a) a is final and you cannot assign it in init ; D(4)是假的,因为a) a是最终的,你不能在init分配它 ; b) there is no guarantee that init will be called; b)无法保证会调用init ; c) init doesn't set the third element; c) init不设置第三个元素;

for snippet C You cannot give dimensions ( Size ) while initializing for snippet D you should initialize final variable. 对于片段C您在初始化片段D时不能给出尺寸(大小),您应该初始化最终变量。 It cannot be initialized later. 它无法在以后初始化。

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. 由于“static void init()”是一个方法,它不会在构造函数之前运行,因此最终变量不会被初始化。 Hence it is an compile time error. 因此它是编译时错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM