Why enhanced for loop is not performing the null checking
Wh开发者_如何学Goy the enhanced for loop is not performing null checking before iterating over the collection.
If you mean that this would go bang:
int[] array = null;
for (int x : array) {
}
... then I think it's entirely proper for that to throw a NullPointerException
. The alternative would be for it to silently swallow the null, and treat that as equivalent to an empty array. That's not the approach Java takes anywhere else - why should this be different? It would make the language inconsistent.
The one place I wish there were more handling (but explicit handling) is switching on an enum - it would be nice to be able to provide a case for null, to avoid checking for that one special value beforehand. But that's a very different construct, which is specifically trying to take different actions for different values.
I kind of afraid to assert against Jon Skeet... :| ... But what a hell... what do you think about this scenario?:
`
findMoney(List<Places> places){
int money = 0;
for(Place place : places){
money += searchWithCare(place);
}
return money;
}
`
If I ask some client to tell me where to look and he tells me nothing. Do you think is better here to throw a NullPointerException? May be manage the call to this method so if parameter is null not call it?.... I think that return 0 is a consistent response because no error is here. I believe Exceptions are made to manage flow of code and I dont see why should I change the flow in this kind of situation. Return a cero or even a null could be a good response, couldnt it be?
So what about this solution? `
findMoney(List<Places> places){
int money = 0;
for(Place place : places == null ?Collections.<Place>emptyList():places){
money += searchWithCare(place);
}
return money;
}
`
The code must be like this:
for (AnyObject anyObject : checkIsEmpty(anyObjectList)) {
System.out.println(anyObject.doSomething());
}
private <T> Iterable<T> checkIsEmpty(Iterable<T> iterable) {
return iterable == null ? Collections.<T>emptyList() : iterable;
}
精彩评论