Java 使数组元素为空
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2189464/
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
making elements of an array null
提问by user69514
are these two the same things?
这两个是同一个东西吗?
for(int i=0; i<array.length; i++){
array[i] = null;
}
and
和
array = null;
回答by John Boker
No, the first one makes each element of the array null, the length of the array will still be array.length, the second will set the array variable to null.
不,第一个使数组的每个元素为空,数组的长度仍然是array.length,第二个将数组变量设置为空。
回答by SyntaxT3rr0r
Not at all.
一点也不。
In the first case you're setting all the references in your array to null.
在第一种情况下,您将数组中的所有引用设置为 null。
In the second case you're setting the very reference to the array itself to null.
在第二种情况下,您将对数组本身的引用设置为空。
回答by codaddict
A small snippet to show the difference:
一个显示差异的小片段:
// declare a array variable that can hold a reference.
String [] array;
// make it null, to indicate it does not refer anything.
array = null;
// at this point there is just a array var initialized to null but no actual array.
// now allocate an array.
array = new String[3];
// now make the individual array elements null..although they already are null.
for(int i=0;i<array.length;i++)
{
array[i] = null;
}
// at this point we have a array variable, holding reference to an array,
// whose individual elements are null.
回答by Lombo
No, it is not the same.
不,它不一样。
As a matter of fact, for the first snippet of code to run correctly, the array variable should be declared and initialized like this (for example)
事实上,为了正确运行第一个代码片段,应该像这样声明和初始化数组变量(例如)
Object[] array = new Object[5];
This creates an array of 5 elements with each element having a null
value.
这将创建一个包含 5 个元素的数组,每个元素都有一个null
值。
Once you have this, in the first example what you are doing is assigning a null value to each of the array[i]
elements. array
will not be null
. So you should have something like this.
一旦你有了这个,在第一个例子中你所做的是为每个array[i]
元素分配一个空值。array
不会null
。所以你应该有这样的东西。
array ->
数组 ->
- array[0] -> null
- array[1] -> null
- array[2] -> null
- array[3] -> null
- array[4] -> null
- 数组[0] -> 空
- 数组[1] -> 空
- 数组[2] -> 空
- 数组[3] -> 空
- 数组[4] -> 空
By doing array = null
you are saying that the array no longer references that array of elements. Now you should have
通过这样做,array = null
您是说该数组不再引用该元素数组。现在你应该有
array -> null
数组 -> 空
回答by Tris
Neither of them will work! If you have an array of integers and you try to make an element null you can't do arr[i]=null; because integer cannot be converted to null.
他们都不会工作!如果你有一个整数数组并且你试图让一个元素为空,你不能做 arr[i]=null; 因为整数不能转换为空。