空检查增强for循环 [英] Null check in an enhanced for loop
问题描述
if(someList!= null)
$ b
{
for(Object object:someList){
//做任何
}
}
或者
pre $ if $($ $ $ $ $ return $; //或者抛出ex
(Object object:someList){
//做任何
}
可能没有其他办法。他们应该把它放在中,如果它是null,那么不要运行循环? >解决方案
您应该更好地验证从哪里获取该列表。
一个空列表就是你所需要的,因为一个空列表不会失败。
这个列表从别的地方,不知道是否可以或不可以,你可以创建一个实用的方法,并像这样使用它:
for(Object o:safe(list)){
//做任何
}
当然 safe 应该是:
public静态列表安全(其他){
return other == null? Collections.EMPTY_LIST:other;
}
What is the best way to guard against null in a for loop in Java?
This seems ugly :
if (someList != null) {
for (Object object : someList) {
// do whatever
}
}
Or
if (someList == null) {
return; // Or throw ex
}
for (Object object : someList) {
// do whatever
}
There might not be any other way. Should they have put it in the for
construct itself, if it is null then don't run the loop?
You should better verify where you get that list from.
An empty list is all you need, because an empty list won't fail.
If you get this list from somewhere else and don't know if it is ok or not you could create a utility method and use it like this:
for( Object o : safe( list ) ) {
// do whatever
}
And of course safe
would be:
public static List safe( List other ) {
return other == null ? Collections.EMPTY_LIST : other;
}
这篇关于空检查增强for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!