Why the enhanced for loop is not performing null checking before iterating over the collection.
The drawback of the enhanced for loop is that it cannot traverse the elements in reverse order. Here, you do not have the option to skip any element because it does not work on an index basis. Moreover, you cannot traverse the odd or even elements only.
The following java segment will result a NullPointException, since the variable list is null, which is pass to the for-each loop. Include arr!= null expression could reduce code nesting. If you know that arr is not null already, would you like it to go through an extra useless null check?
1.2 In Java 8, we can use forEach to loop a Map and print out its entries. 1.3 For the Map 's key or value containing null , the forEach will print null . P.S The normal way to loop a Map will print the same above output. 1.4 If we do not want to print the null key, add a simple null checking inside the forEach .
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;
}
`
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With