are these two the same things?
for(int i=0; i<array.length; i++){
array[i] = null;
}
and
array = null;
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.
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, 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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With