java:原始数组——它们是否已初始化?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2944535/
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
java: primitive arrays -- are they initialized?
提问by Jason S
If I use a statement in my code like
如果我在我的代码中使用像
int[] a = new int[42];
Will it initialize the array to anything in particular? (e.g. 0) I seem to remember this is documented somewhere but I am not sure what to search for.
它会将数组初始化为任何特别的东西吗?(例如 0)我似乎记得这是在某处记录的,但我不确定要搜索什么。
采纳答案by p00ya
At 15.10 Array Creation Expressionsthe JLS says
JLS在15.10 Array Creation Expressions说
[...] a single-dimensional array is created of the specified length, and each component of the array is initialized to its default value
[...] 创建指定长度的一维数组,并将数组的每个组件初始化为其默认值
and at 4.12.5 Initial Values of Variablesit says:
在4.12.5 Initial Values of Variables它说:
For type
int
, the default value is zero, that is,0
.
对于 type
int
,默认值为零,即0
。
回答by Bozhidar Batsov
When created, arrays are automatically initialized with the default value of their type - in your case that would be 0
. The default is false
for boolean
and null
for all reference types.
创建时,数组会自动使用其类型的默认值进行初始化 - 在您的情况下为0
. 默认值是false
为boolean
与null
所有引用类型。
回答by Haldean Brown
All elements in the array are initialized to zero. I haven't been able to find evidence of that in the Java documentation but I just ran this to confirm:
数组中的所有元素都初始化为零。我一直无法在 Java 文档中找到证据,但我只是运行它来确认:
int[] arrayTest = new int[10];
System.out.println(arrayTest[5]) // prints zero
回答by OscarRyz
The array would be initialized with 42 0s
数组将用 42 个 0 初始化
For other data types it would be initialized with the default value ie.
对于其他数据类型,它将使用默认值进行初始化,即。
new boolean[42]; // would have 42 falses
new double[42]; // would have 42 0.0 ( or 0.0D )
new float[42]; // 42 0.0fs
new long[42]; // 42 0Ls
And so on.
等等。
For objects in general it would be null:
对于一般的对象,它将为空:
String [] sa = new String[42]; // 42 nulls
Date [] da = new Date[42]; // 42 nulls