检测数组中的空引用
我想检测数组的子范围是否包含空引用。不知怎的,像这样:
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;
}
Java库中是否有这样的方法,这样我就不必手动循环数组?也许我被 C++ 对以算法为中心的代码的出色支持宠坏了,我可以在其中编写:
#include <algorithm>
bool found_null = (std::find(array + from, array + to, 0) != array + to);
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);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
检查是否
Arrays.asList(myArray).contains(null)
。要检查数组的一部分,请检查
这是否不会创建不必要的数组副本;
asList
和subList
都创建ArrayList
和RandomAccessSubList
对象包装原始数组而不复制它。Check whether
Arrays.asList(myArray).contains(null)
.To check part of an array, check whether
This will not create unnecessary copies of the array; both
asList
andsubList
createArrayList
andRandomAccessSubList
objects that wrap the original array without copying it.Apache commons-lang 为您提供
ArrayUtils.contains(array, null)
对于范围:ArrayUtils.contains(Arrays.copyOfRange(array, from, to), null)
Apache commons-lang gives you
ArrayUtils.contains(array, null)
For the range:
ArrayUtils.contains(Arrays.copyOfRange(array, from, to), null)