I guess an other way to ask the same question is how to know the number of null pointing elements in an array?
int[] arrayOfEffectiveSizeTen = new int[10];
// some black box in which the content of the array is changed
calculateAverage(arrayOfEffectiveSizeTen) //how can you do this for instance?
Do you really have to do something like this in a for
loop with i < arrayOfEffectiveSizeTen.length
?
arrayOfEffectiveSizeTen[i] == null ? nullPointingElement++ : elementInArray++;
I couldn't find any duplicate question. Which I found weird. In my particular case it's about Java.
In Java, you have to differentiate between primitive types and reference types.
When an array is initialized with
new <sometype>[size]
, all its elements are set to a default value. Forint
,long
,byte
etc, the value is 0. So you can run an average function on such an array, and you will get an average of 0.If the type is boolean, the initial value is
false
.If the type is any object type (class), including the well-known types such as
String
,Integer
, etc, the default values are all nulls.So basically, when you create an array, if it's of a primitive type, then you can say, by your definition, that its length is its "effective size", because
0
orfalse
are legitimate values.If it's of a reference type, then when you create it, its effective size - by your definition - is zero, because there are no non-null elements.
However, using
new
is not the only way to initialize an array. You can, for example, use something like:Note that this is an array of type
Integer
, which is a reference type, rather thanint
, the primitive type. If you had initialized it withnew Integer[3]
you would have had all nulls. But when you initialize it as I showed, it contains references to threeInteger
objects containing the numbers 5, 17 and 32 respectively. So you can say its effective size is the same as its length.Note, however, that it's also legitimate to write something like:
With all that in mind, the answer to the question "How do I know how many null values are in the array" is:
new
, then all its elements are null.{...}
, or assigned values since its initialization, you have no way to know how many nulls are in it, except by looping and counting.