My question is quite clear.
I have a list and I want to be sure that it has at least one not null element. And that too, without looping (performance measurement).
list.size()
Run Code Online (Sandbox Code Playgroud)
is definitely not helpful here. Because if the list contains 5 null values, then also its size will be 5.
Please note that, I'm not asking for a list that cannot contain null.
List没有循环的标准实现无法显式或隐式地执行此操作1.ListAPI 不支持此功能,并且没有任何标准列表类作为专用操作包含在内.
避免循环的唯一方法是创建一个特殊的自定义List实现null,并保留null列表中元素数量的计数.这种方法的缺点是列表上的更新操作更昂贵,因为他们需要测试以查看计数器是否需要更改.
请注意,使用手动编码循环通常并不昂贵,因为只要看到非null元素,就可以停止循环.
1 - 如果你担心效率,那么某种方法中的隐式循环Collections.frequency可能比明确用于此目的的手动循环要昂贵得多.
跟进
我没有创建或填写列表.我从一些我无法改变的代码中获取了已经生成的列表.
在这种情况下,像下面这样的循环是最快的解决方案:
boolean empty = true;
for (SomeType t : list) {
if (t != null) {
empty = false;
break;
}
}
Run Code Online (Sandbox Code Playgroud)
如果列表是a ,则索引可能稍微快一些ArrayList,但不是a LinkedList.