我正在查看我的旧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,它插入随机数的空值(稍后在代码中,实际的整数值)。
谢谢!
没有更有效的方法。唯一能做的就是以更优雅的方式写出来:
List<Something> l;
boolean nonNullElemExist= false;
for (Something s: l) {
if (s != null) {
nonNullElemExist = true;
break;
}
}
// use of nonNullElemExist;
实际上,这可能更有效,因为它使用Iterator
并且Hotspot编译器有更多信息来优化使用size()
和get()
。
好吧,你可以为初学者使用更少的代码:
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);
}
它不是仅包含null
值的检测,但它可能足以在您的列表中使用contains(null)
方法。
只需检查它对我有用。希望也适合你!
if (arrayListSubQues!=null){
return true;}
else {
return false }
我用来做这样的事情:
// 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
}