在for-each循环迭代开始之前,有没有办法避免空检查? [英] Is there a way to avoid null check before the for-each loop iteration starts?

查看:100
本文介绍了在for-each循环迭代开始之前,有没有办法避免空检查?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每次我必须迭代一个集合,最终在for-each循环迭代开始之前检查null。像这样:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆