我想检测数组的子范围是否包含空引用。有点像这样:
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);
最佳答案
检查是否Arrays.asList(myArray).contains(null)
。
要检查数组的一部分,检查是否
Arrays.asList(myArray).subList(from, to).contains(null)
这不会创建不必要的数组拷贝; asList
和 subList
都创建 ArrayList
和 RandomAccessSubList
包装原始数组而不复制它的对象。
关于java - 检测数组中的空引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4729792/