are these two the same things?
for(int i=0; i<array.length; i++){
array[i] = null;
}
and
array = null;
are these two the same things?
for(int i=0; i<array.length; i++){
array[i] = null;
}
and
array = null;
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.
Not at all.
In the first case you're setting all the references in your array to null.
In the second case you're setting the very reference to the array itself to null.
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.
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.
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 ->
By doing array = null
you are saying that the array no longer references that array of elements. Now you should have
array -> null