java - 检测数组中的空引用

标签 java c++ arrays algorithm null

我想检测数组的子范围是否包含空引用。有点像这样:

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)

这不会创建不必要的数组拷贝; asListsubList 都创建 ArrayListRandomAccessSubList包装原始数组而不复制它的对象。

关于java - 检测数组中的空引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4729792/

相关文章:

ios - 在调用 API 之前从数组中移除对象

javascript - 如何按字符串值对数组中的对象数组进行排序?

python - 在另一个数组的条件下更改 numpy 数组

java - Ant 构建文件中的 GWT 编译器错误

java.net.UnknownHostException : Unable to resolve host "s3-ap-northeast-1.amazonaws.com": No address associated with hostname

java - 抽屉导航,它的 fragment 按钮找不到正确的 Action 监听器

c++ - 命名空间到底是什么,为什么有必要

c++ - Lambda 内循环

java - 将 GWT-RPC-Applicaton 部署到 OpenShift 时出现 ClassNotFoundException

c++ - 为什么需要空构造函数?