array = null or array.length = 0

  • Thread starter Thread starter Rene
  • Start date Start date
R

Rene

I have an array that may or may not contain data during the course of its
life. When I first instantiate my class level array reference I set the
array to null:
int[] xyz = null;
But I am thinking of initializing it to zero
int[] xyz = new int[0]

There is no good reason why I need to do this except that it feels more
accurate to say that an array contains zero items rather than null.

Can anyone share some opinions on why I should go one way versus another?
Performance issues, good practices, etc?

Thank you.
 
Rene,

From a performance standpoint, you want to use null, because you would
always have this object reference hanging around. Of course, in the scheme
of things, it's probably insignificant, so I wouldn't even say that this is
a good reason to use null.

I think that what you should do is encapsulate access to the variable in
a property, and make the variable private. This way, when someone assigns
to the variable, if the length of the array is zero, or null, you can set it
to a consistent state in the private variable. This way, when you return
the private variable through the property, you can be assured it is always
returning what you want (a null value, or an array with length zero).

Hope this helps.
 
Back
Top