Search code examples
javaarraysvariable-length-array

Effective size versus actual size of an array, how to get to know the effective size?


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.


Solution

  • 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. For int, 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 or false 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:

    Integer[] intObjects = { 5, 17, 32 };
    

    Note that this is an array of type Integer, which is a reference type, rather than int, the primitive type. If you had initialized it with new Integer[3] you would have had all nulls. But when you initialize it as I showed, it contains references to three Integer 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:

    Integer[] intObjects = { 5, null, 32 };
    

    With all that in mind, the answer to the question "How do I know how many null values are in the array" is:

    1. If the array is of primitive type, there are no null values. It contains legitimate values, even if they are zero/false.
    2. If the array is of a reference type, and you initialized it with new, then all its elements are null.
    3. If the array is of a reference type, and you initialized it with {...}, or assigned values since its initialization, you have no way to know how many nulls are in it, except by looping and counting.