【发布时间】:2011-01-16 00:59:26
【问题描述】:
在 Java 的 for 循环中防止 null 的最佳方法是什么?
这看起来很丑:
if (someList != null) {
for (Object object : someList) {
// do whatever
}
}
或者
if (someList == null) {
return; // Or throw ex
}
for (Object object : someList) {
// do whatever
}
可能没有其他方法。他们是否应该将其放入 for 构造本身,如果它为 null 则不运行循环?
【问题讨论】:
-
你最好还是扔一个 NPE。
null与空集合不同。 -
@GregMattes 2 月的问题与 10 月的问题是如何重复的?
-
只需要使用Collections.nonNullElementsIn(...):stackoverflow.com/a/34913556/5637185
标签: java syntax loops for-loop