8

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);
fredoverflow
  • 256,549
  • 94
  • 388
  • 662

2 Answers2

26

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.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • you'd also have to call copyOfRange or something in order to only get the range he wants to search, in which case, it seems like iterating over the array yourself is going to be the most cost effective solution. – digitaljoel Jan 18 '11 at 22:36
  • 1
    @digitaljoel using `asList` and `subList` doesn't duplicate the data - it uses the same backing array, so it is as efficient (in terms of space at least) – Bozho Jan 18 '11 at 22:45
  • I have never understood why the Arrays class does not have a simple contains operation. Having to rely on Apache for this seems superfluous. – Uri Jan 18 '11 at 23:05
  • Ah, I missed the subList call in the second code sample. Sorry about that. – digitaljoel Jan 18 '11 at 23:06
  • @Fred: He's referring to the other answer. – SLaks Jan 18 '11 at 23:11
  • @Fred: I probably should have stated this differently as "I feel this should have been part of the Arrays class, but since it is not, the common course of action is to rely on Apache". – Uri Jan 19 '11 at 14:16
4

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

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

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140