Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

making elements of an array null

Tags:

java

arrays

null

are these two the same things?

for(int i=0; i<array.length; i++){
array[i] = null;
}

and

array = null;
like image 930
user69514 Avatar asked Feb 03 '10 03:02

user69514


4 Answers

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.

like image 60
Tris Avatar answered Oct 11 '22 10:10

Tris


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.
like image 19
codaddict Avatar answered Nov 08 '22 14:11

codaddict


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.

like image 9
John Boker Avatar answered Nov 08 '22 14:11

John Boker


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 ->

  • array[0] -> null
  • array[1] -> null
  • array[2] -> null
  • array[3] -> null
  • array[4] -> null

By doing array = null you are saying that the array no longer references that array of elements. Now you should have

array -> null

like image 5
Lombo Avatar answered Nov 08 '22 14:11

Lombo