user69514
user69514

Reputation: 27629

making elements of an array null

are these two the same things?

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

and

array = null;

Upvotes: 10

Views: 107692

Answers (5)

Tris
Tris

Reputation: 29

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.

Upvotes: 1

codaddict
codaddict

Reputation: 454990

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.

Upvotes: 19

Lombo
Lombo

Reputation: 12235

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

Upvotes: 6

SyntaxT3rr0r
SyntaxT3rr0r

Reputation: 28293

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.

Upvotes: 0

John Boker
John Boker

Reputation: 83699

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.

Upvotes: 9

Related Questions