0

我有一个简单的问题,我似乎找不到答案。我认为这真的很简单,我可以把它当作语言怪癖。

 int[] newArray=new int[5];

将初始化一个数组并在所有 5 个位置上都为零。

newArray[4]=0; 
//versus not assigning any value to specific position newArray[4]

两个是一样的吗?如果不是,如何区分这两者?

如何区分创建数组时自动放置的零与程序中某个时刻分配的零?

我问这个的主要原因是我有一个程序,它在数组中的随机位置分配一些整数值,也可以是 0。在搜索时,我想知道程序分配了哪些零,哪些是初始化的零。

4

4 回答 4

2

Since you put ints in your array they are equivalent because the default value of int is 0. You won't be able to differentiate the two because 0 equals 0.

If you use Integer however the array will be initialized with nulls. In that case you can tell whether a value was set or not.

If you want to be able to tell the difference you can use references.

于 2013-10-08T12:34:29.560 回答
1

int[] newArray=new int[5] will initialize all elements to 0 by default.

newArray[4]=0 will set the value of 5th element to 0. All other's will be by default anyways. So there's no difference between the two.

To understand this set newArray[4]=10 instead.

Now the array content is {0,0,0,0,10}

于 2013-10-08T12:35:14.247 回答
1

Why do you say quirk? It's clear that every reference and primitive has an initial default value in Java. For int it's 0. For references it's null.

于 2013-10-08T12:35:28.763 回答
0

如果将变量实例化为类的成员,它将具有默认值:数字为 0,对象为 null。但是,如果您在方法中声明该变量,编译器不会为该变量分配默认值,因此在您设置它之前,它的内容是未定义的。

因此,如果您在方法中执行此操作,则不等效;-)

于 2013-10-08T12:37:27.550 回答