在for-each循环迭代开始之前,有没有办法避免空检查? [英] Is there a way to avoid null check before the for-each loop iteration starts?
问题描述
pre $
if(list1!= null){
for(Object obj:list1){
$ b $ p $是有一个更短的方法,所以我们可以避免写如果块?
注意:我正在使用Java 5,并且会一直使用它。解决方案答案是:没有办法把它缩短。有一些技术,如评论中的,但我没有看到自己使用它们。我认为写一个if块比使用这些技术更好。是的..在任何人再次提到它之前:)理想情况下的代码应该被设置,这样的列表不应该是一个空
Every time I have to iterate over a collection I end up checking for null, just before the iteration of the for-each loop starts. Like this:
if( list1 != null ){
for(Object obj : list1){
}
}
Is there a shorter way, so that we can avoid writing the "if" block ?
Note: I am using Java 5, and will be stuck with it for sometime.
解决方案 I guess the right answer is that: there is no way to make it shorter. There are some techniques such as the ones in the comments, but I don't see myself using them. I think it's better to write a "if" block than to use those techniques. and yes.. before anybody mentions it yet again :) "ideally" the code should be desgined such that list should never be a null
这篇关于在for-each循环迭代开始之前,有没有办法避免空检查?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!