这两个东西是一样的吗?
for(int i=0; i<array.length; i++){
array[i] = null;
}
and
array = null;
以下是一个小片段,用于展示它们之间的区别:
// 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.
不,第一个会使数组的每个元素为null,但是数组的长度仍然是array.length。而第二个会将数组变量设置为null。
Object[] array = new Object[5];
null
值。array[i]
元素。 array
不会是null
。因此,你应该有类似于以下内容的东西。array = null
,你正在表示该数组不再引用那个元素数组。现在你应该有两种方法都不可行!如果您有一个整数数组,并尝试将元素设置为null,则无法完成操作。
arr[i]=null;
因为整数不能转换为null。
完全不是这样。
在第一种情况下,您将数组中的所有引用都设置为 null。
在第二种情况下,您将数组本身的引用设置为 null。