检查ArrayList是否只包含null值的方法。
I was looking through the code for an old Android application of mine, and I saw one thing I did to the effect of this:
我正在查看我的一个旧的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;
There has to be a more efficient way of doing this -- but what is it?
必须有一种更有效的方法来做到这一点——但它是什么呢?
emptyArray is defined as an ArrayList of Integers, which are inserted with a random number of null values (And later in the code, actual integer values).
emptyArray定义为一个整数的ArrayList,它插入了随机数的空值(在后面的代码中是实际的整数值)。
Thanks!
谢谢!
4 个解决方案
#1
6
There is no more efficient way. The only thing is you can do, is write it in more elegant way:
没有更有效的方法。你唯一能做的就是,用更优雅的方式写出来:
List<Something> l;
boolean nonNullElemExist= false;
for (Something s: l) {
if (s != null) {
nonNullElemExist = true;
break;
}
}
// use of nonNullElemExist;
Actually, it is possible that this is more efficient, since it uses Iterator
and the Hotspot compiler has more info to optimize instead using size()
and get()
.
实际上,这可能更有效,因为它使用迭代器,Hotspot编译器有更多的信息来优化,而不是使用size()和get()。