javaarraysnull

How to determine length of occupied spaces in arrays


I have an array and I need to check the number of elements which are not null.

For example:

String carlist[] =new String[50]

carlist[0] = ferrari
carlist[1] = bentley

//all other values will be null.

How do I find out the answer, 2, which is the number of occupied places?


Solution

  • This will give you the number of non-null elements in an array:

    int count = 0;
    for (String car : carlist) {
        if(car != null) {
            count++;
        }
    }
    

    Alternatively, if the array is populated sequentially so there are no nulls until the end, and you're working with a large dataset, you can use a binary search to find the first null more efficiently:

    int count = Arrays.binarySearch(carlist, null, Comparator.nullsLast((a, b) -> 0));
    if (count < 0) {
        count = carlist.length;
    }
    

    This comparator basically says "ignore the relative order of the values and just assume nulls come last." If the search returns a positive value, that's the index of the first null value, which is equivalent to the length of the non-null segment. If it's negative, it means no nulls were found, so the non-null count is the same as the array length.