检查ArrayList是否仅包含空值的方法

问题描述 投票:12回答:5

我正在查看我的旧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被定义为整数的ArrayList,它插入随机数的空值(稍后在代码中,实际的整数值)。

谢谢!

java android
5个回答
6
投票

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

List<Something> l;

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

// use of nonNullElemExist;

实际上,这可能更有效,因为它使用Iterator并且Hotspot编译器有更多信息来优化使用size()get()


20
投票

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

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);
}

0
投票

它不是仅包含null值的检测,但它可能足以在您的列表中使用contains(null)方法。


0
投票

只需检查它对我有用。希望也适合你!

    if (arrayListSubQues!=null){
return true;}
else {
return false }

-1
投票

我用来做这样的事情:

// Simple loop to remove all 'null' from the list or a copy of the list
while array.remove(null) {
    array.remove(null);
}

if (CollectionUtils.isEmpty(array)) {
    // the list contained only nulls
}
© www.soinside.com 2019 - 2024. All rights reserved.