Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect null reference in an array

I want to detect whether or not a subrange of an array contains the null reference. Somehow like this:

public static <T> boolean containsNull
(T[] array, int fromInclusive, int toExclusive)
{
    for (int i = fromInclusive; i < toExclusive; ++i)
    {
        if (array[i] == null) return true;
    }
    return false;
}

Is there a method like this in the Java library so I don't have to manually loop over the array? Maybe I have been spoiled by C++'s excellent support for algorithmically focused code, where I can just write:

#include <algorithm>

bool found_null = (std::find(array + from, array + to, 0) != array + to);
like image 991
fredoverflow Avatar asked Jan 18 '11 22:01

fredoverflow


1 Answers

Check whether Arrays.asList(myArray).contains(null).

To check part of an array, check whether

Arrays.asList(myArray).subList(from, to).contains(null)

This will not create unnecessary copies of the array; both asList and subList create ArrayList and RandomAccessSubList objects that wrap the original array without copying it.

like image 107
SLaks Avatar answered Oct 15 '22 06:10

SLaks