检查数组列表是否仅包含空值的方法

2022-09-04 06:46:39

我正在查看我的一个旧Android应用程序的代码,我看到了一件大意如此的事情:

        boolean emptyArray = true;
        for (int i = 0; i < array.size(); i++)
        {
            if (array.get(i) != null)
            {
                    emptyArray = false;
                    break;
            }
        }
        if (emptyArray == true)
        {
            return true;
        }
        return false;

必须有一种更有效的方法来做到这一点 - 但它是什么?

emptyArray 被定义为 Integer 的 ArrayList,这些 Integers 使用随机数量的 null 值插入(在代码的后面,实际整数值)。

谢谢!


答案 1

好吧,你可以为初学者使用更少的代码:

public boolean isAllNulls(Iterable<?> array) {
    for (Object element : array)
        if (element != null) return false;
    return true;
}

使用此代码,您还可以传入更多种类的集合。


Java 8 更新:

public static boolean isAllNulls(Iterable<?> array) {
    return StreamSupport.stream(array.spliterator(), true).allMatch(o -> o == null);
}

答案 2

没有更有效的方法。唯一能做的就是,就是用更优雅的方式写出来:

List<Something> l;

boolean nonNullElemExist= false;
for (Something s: l) {
  if (s != null) {
     nonNullElemExist = true;
     break;
  }
}

// use of nonNullElemExist;

实际上,这可能更有效率,因为它使用并且Hotspot编译器具有更多信息来优化,而不是使用和。Iteratorsize()get()


推荐