在实践中,是能够更好地返回像一个空列表此:
return Collections.emptyList();
Run Code Online (Sandbox Code Playgroud)
或者像这样:
return new ArrayList<Foo>();
Run Code Online (Sandbox Code Playgroud)
或者这完全取决于你要对返回的列表做什么?
在Java中的for循环中防止null的最佳方法是什么?
这看起来很难看:
if (someList != null) {
for (Object object : someList) {
// do whatever
}
}
Run Code Online (Sandbox Code Playgroud)
要么
if (someList == null) {
return; // Or throw ex
}
for (Object object : someList) {
// do whatever
}
Run Code Online (Sandbox Code Playgroud)
可能没有任何其他方式.他们应该把它放在for
构造本身,如果它是null,那么不要运行循环?
在我的代码NullPointerException
中,当a List
为null 时,我通常使用这种方法来避免s in语句:
if (myList != null && myList.size() > 0) {
for ( MyObj obj : myList ) {
System.out.println("MyObjStr: "+obj);
}
}
Run Code Online (Sandbox Code Playgroud)
是否有其他方法可以在不写"if"语句的情况下执行相同操作,但使用相同的"for"语句?
鉴于Collection<Object> foo
,我通常会在迭代之前进行此检查:
if (foo != null && !foo.isEmpty()) {
for (Object f : foo) {
// ...
}
}
Run Code Online (Sandbox Code Playgroud)
我只是想知道,这被认为是最佳实践吗?isEmpty()
检查不应该是多余的,因为for()
它只会忽略一个空集合而不会抛出错误?
null
检查如何- 这是必要的还是有办法for()
简单地忽略null
集合?(没有尝试捕捉 for 循环)