Array null reference detection

I want to determine if an array subrange contains a null reference. Anyway:

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 such a way in the Java library, so I don't need to manually iterate over the array? Perhaps I was spoiled by C ++ with excellent support for algorithmically focused code, where I can simply write:

#include <algorithm>

bool found_null = (std::find(array + from, array + to, 0) != array + to);
+5
source share
2 answers

Check if there is Arrays.asList(myArray).contains(null).

To check part of the array, check

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

This will not create unnecessary copies of the array; the two asListand subListcreate ArrayListand RandomAccessSubListobjects that wrap the original array, without copying.

+20
source

Apache commons-lang ArrayUtils.contains(array, null)

: ArrayUtils.contains(Arrays.copyOfRange(array, from, to), null)

+3

All Articles