java 检测数组中的空引用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4729792/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Detect null reference in an array
提问by fredoverflow
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:
Java 库中是否有这样的方法,因此我不必手动遍历数组?也许我被 C++ 对算法重点代码的出色支持所宠坏,我可以在其中编写:
#include <algorithm>
bool found_null = (std::find(array + from, array + to, 0) != array + to);
回答by SLaks
Check whether Arrays.asList(myArray).contains(null)
.
检查是否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.
这不会创建不必要的数组副本;双方asList
并subList
创建ArrayList
和RandomAccessSubList
对象那套原始数组不复制它。
回答by Bozho
Apache commons-langgives you ArrayUtils.contains(array, null)
Apache commons-lang给你ArrayUtils.contains(array, null)
For the range: ArrayUtils.contains(Arrays.copyOfRange(array, from, to), null)
对于范围: ArrayUtils.contains(Arrays.copyOfRange(array, from, to), null)