开发者

Detect null reference in an array

开发者 https://www.devze.com 2023-02-05 22:59 出处:网络
I want to detect whether or not a subrange of an array contains the null reference. Somehow like this:

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] =开发者_如何学JAVA= 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);


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.


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

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

0

精彩评论

暂无评论...
验证码 换一张
取 消