增强了对象的循环和空检查 [英] Enhanced for loop and null check of objects
问题描述
让我说我有以下代码:
for (AnyObject anyObject : anyObjectList) {
System.out.println(anyObject.doSomething());
}
我的问题是:我读到它有可能在至少某种列表类型中添加null. 如果我说对了:在访问迭代类的方法之前,不总是应该有一个null检查吗? 我只是问,因为到目前为止我从未见过像这样的空检查增强的for循环:
My question is: I read that its possible to add null to at least some kind of list types. If im right: shouldn't be there always a null check before you access the method of the iterated class? Im just asking because i have never seen so far a enhanced for loop with a null check like this for example:
for (AnyObject anyObject : anyObjectList) {
if (anyObject != null) {
System.out.println(anyObject.doSomething());
}
}
推荐答案
实际上,您经常想知道列表中是否有随机的null
,而不应该出现.您的第一个代码段将引发异常以指示问题,而第二个代码段将静默使用该错误.
Actually you'd often want to know if there is a random null
in your list when there shouldn't be. Your first snippet will throw an exception indicating the problem, but your second will consume the error silently.
您还可以执行以下操作:
You could also do something like this:
for (AnyObject anyObject : anyObjectList) {
if (anyObject != null) {
System.out.println(anyObject.doSomething());
} else {
/* something went wrong -- report error, debugging info, etc. */
}
}
这篇关于增强了对象的循环和空检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!