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);
2
  • I fear you'll have to copy the code from your post into your code base! Commented Jan 18, 2011 at 22:31
  • If you are interested in more library goodness, (besides apache common-lang) check out guava, which includes google's collections library. Commented Jan 19, 2011 at 18:03

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

6 Comments

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 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)
I have never understood why the Arrays class does not have a simple contains operation. Having to rely on Apache for this seems superfluous.
Ah, I missed the subList call in the second code sample. Sorry about that.
@Fred: He's referring to the other answer.
|
5

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.