Null check in an enhanced for loop
There might not be any other way. Should they have put it in the for construct itself, if it is null then don’t run the loop?
11 Answers 11
You should better verify where you get that list from.
An empty list is all you need, because an empty list won’t fail.
If you get this list from somewhere else and don’t know if it is ok or not you could create a utility method and use it like this:
And of course safe would be:
public static List safe( List other )
@Jon: I have always asked my self, what was the use of that emptyList java.sun.com/j2se/1.5.0/docs/api/java/util/… What’s IIRC?
IIRC = «If I recall correctly». And yes, there is a singleton instance that is returned for all calls to Collections.emptyList().
Both Collections.emptyList and Collections.EMPTY_LIST return public static final List EMPTY_LIST = new EmptyList
You could potentially write a helper method which returned an empty sequence if you passed in null:
public static Iterable emptyIfNull(Iterable iterable) < return iterable == null ? Collections.emptyList() : iterable; >
for (Object object : emptyIfNull(someList))
I don’t think I’d actually do that though — I’d usually use your second form. In particular, the «or throw ex» is important — if it really shouldn’t be null, you should definitely throw an exception. You know that something has gone wrong, but you don’t know the extent of the damage. Abort early.
Be careful using this method: because of use of Collections class, the use of this method involve your list te be immutable
@JonSkeet you can see that emptyList() of Collections class return an immutable list : docs.oracle.com/javase/8/docs/api/java/util/… so if the user do not want to have his list immutable it can be problematic
@tanorix: But the point of this question is about iterating over the returned value. That doesn’t modify it. That’s why the return type of emptyIfNull is Iterable — there’s the unfortunate remove method on Iterator , but that’s the only mutable aspect of it (and if you’ve got an empty collection, why are you trying to remove anything from it?) It’s not clear what you’re objecting to here.
It’s already 2017, and you can now use Apache Commons Collections4
for(Object obj : ListUtils.emptyIfNull(list1)) < // Do your stuff >
You can do the same null-safe check to other Collection classes with CollectionUtils.emptyIfNull .
Will work though creates unnecessary list object. A CollectionUtils.ifNotEmpty may be more verbose but more efficient and faster. Not that it would matter much.
@Lawrence, the method doesn’t create new list objects, it uses Collections.emptyList() internally, which in its turn always returns the same preallocated empty unmodifiable list.
for (Object object : Optional.ofNullable(someList).orElse(Collections.emptyList())) < // do whatever >
Its more verbose than simple ternary operator like someList != null ? someList : Collections.emptyList() and also creates and immediately throws away an instance of Optional object.
how are these monster lines more elegant than a simple if(someList==null) statement. Let’s write a bank application in one line.
Use ArrayUtils.nullToEmpty from the commons-lang library for Arrays
for( Object o : ArrayUtils.nullToEmpty(list) ) < // do whatever >
This functionality exists in the commons-lang library, which is included in most Java projects.
// ArrayUtils.nullToEmpty source code public static Object[] nullToEmpty(final Object[] array) < if (isEmpty(array)) < return EMPTY_OBJECT_ARRAY; >return array; > // ArrayUtils.isEmpty source code public static boolean isEmpty(final Object[] array)
This is the same as the answer given by @OscarRyz, but for the sake of the DRY mantra, I believe it is worth noting. See the commons-lang project page. Here is the nullToEmpty API documentation and source
Maven entry to include commons-lang in your project if it is not already.
org.apache.commons commons-lang3 3.4
Unfortunately, commons-lang doesn’t provide this functionality for List types. In this case you would have to use a helper method as previously mentioned.
public static List nullToEmpty(List list) < if(list == null || list.isEmpty()) < return Collections.emptyList(); >return list; >
How to perform null check in java 8
but don’t. Look at all all that extra stuff you’d have to write.
Just use a plain old null check, like you have in your code already.
As the Answer by Andy Turner suggest, writing a plain null check is best here.
Objects.nonNull
But Java 8 does offer one minor improvement: methods on the Objects utility class for the null check.
So your code would like this.
List names = service.serviceCall(); if( Objects.nonNull( names ) )
Objects.requireNonNullElseGet
Another method on Objects can return an alternate object if that suits your situation. For example, if your service call returns null list, perhaps you should substitute an empty list. Call Objects.requireNonNullElseGet .
The lambda passed is handled in a lazy manner, not executed unless needed.
List names = Objects.requireNonNullElseGet ( service.serviceCall() , () -> new ArrayList<>( 0 ) // In Java 9 and later, use `List.of()`. ) ; names.forEach( System.out::println );
«But Java 8 does offer one minor improvement: methods on the Objects utility class for the null check.» These methods are not intended to replace null checks. They exist simply to give you a method reference to use inside a method chain, e.g. filter(Objects::nonNull) . Where possible, a plain old null check is preferable.
@AndyTurner Why can’t the Objects methods be used in other contexts? Calls like Objects.nonNull are easier to read and less error-prone than the older syntax of != null . As seen in my last example, using Objects.requireNonNull to provide an alternate object in the case of receiving a null is compact and self-documenting. Your comment leaves me puzzled.
perhaps you like Yoda conditions; I think «objects non null thing» reads far less naturally than «thing is not null». To each his own. But I am referring to the Javadoc which explicitly calls out the intended usage; one must question why the API designers went to the additional effort of saying that. I don’t really feel it’s any less error-prone either: I sometimes invert a condition by mistake, but I don’t think that’s got anything to do with == vs != over isNull vs nonNull . Plus, you have the additional error possibility of an unintentionally primitive argument.
@AndyTurner Regarding «the Javadoc which explicitly calls out the intended usage», I do not find this in the Javadoc. Please cite.
it’s an @apiNote on the methods, in the page you link: «This method exists to be used as a Predicate, filter(Objects::isNull)», «This method exists to be used as a Predicate, filter(Objects::nonNull)».
Avoiding Null Pointer Exception in «for» statement
In my code I usually use this approach to avoid NullPointerException s in for statements when a List is null:
if (myList != null && myList.size() > 0) < for ( MyObj obj : myList ) < System.out.println("MyObjStr: "+obj); >>
Is there another way to do the same without write the «if» statement, but using the same «for» statement?
If you have initialized myList , there is no reason to check if it’s null unless in some point you explicitly assign null to it. Regarding the size, you don’t have to check it.
you can easily avoid collection to be null by calling it’s constructor. In such a case you’ll have non-null, but empty collection. If so, you don’t even need size check
I was wondering that if you are checking that myList
is not null
then where you need to check whether myList
size is greater than 0? What I mean here is that if your list is not null, then it must have size and lists can’t have negative sizes, so I think myList.size() > 0
is not necessary in your case, unless it is initialized.
@AmirAl The size check was to prevent the size from being 0, not from being negative. Even if a list is initialized, it could have a size of 0 (actually it does if you don’t add any item). Anyway, this check is not needed since the for loop does not do anything on an empty list.
6 Answers 6
The check for the size is not needed. Your for-loop will not execute if is there are no objects in the list.
The check for null is only needed, when you are not sure about the object’s state. But when using your own objects (nothing given from outside via arguements e.g.) then there is no need for the null check.
See Avoiding “!= null” statements in Java? for a brilliant explanation why unexperienced developers often exaggregate with null checks.
An elegant way to do this, can be found in a similar post. using
for( Object o : safe( list ) ) < // do whatever >public static List safe( List other )
That beeing said, it’s a good practice to have your methods returning empty Arrays instead of null. For example you can return
return Collections.EMPTY_LIST;
This way you will loop in them safely, and when you get a NPE, you’ll know that something is wrong with your code, not your data. In this context, as @Joffrey said, the NPE will be really welcome
First of all, the size check is not needed. The for loop is skipped if the size is 0.
The null check is a bit more contextual. In general you don’t want to just «avoid NPE». NPE is a good way to notice programming mistakes, so you have to be careful about what needs to be null-checked. Many programmers put null-checks everywhere defensively, because they don’t trust the API contracts anymore.
- If you have an NPE with something that has no reason to be null, then you have done something wrong earlier (here it would be because your collection variable is not initialized). You don’t want to hide that, you want it to explode at your face, so you can fix it right away (Fail fast principle).
- If null is a possible (and meaningful) value for a variable (or if the value comes from an external source), then it needs to be null-checked. However, you have to handle that case, do not just skip the code that produces NPE. If you just skip it, then later code is no more safe than the current piece, and null-checks will be needed again for the same variable.
@ifLoop provided a very good link to another post about this topic, so I copy it here since my answer is accepted: Avoiding “!= null” statements in Java?
Lot of debates about this. I don’t think it should by applied anywhere. For example you don’t want your app to go down if an external service you depend on starts returning null collections.
Of course, I totally agree with you. I don’t say you don’t want null checks. I said you don’t want to just «avoid NPEs». If null is apossible value for an external input (and several other cases), then the check has to be done and handled properly. However, if something has no reason to be null at one point, then don’t put a null check, it hides errors.
In our specific case, the null check is not used to handle a special case, but just to skip the error and hide it, which IMHO is bad.
Is there a way to avoid null check before the for-each loop iteration starts? [duplicate]
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:
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.
Like SLaks said, your collections should not be null instead their size be zero. In that case, the enhanced for loop doesn’t error out.
@ratchet I can’t remove the «if» block. If in case the list1 is null, then there will be NullPointerException
I meant that you type if(list1 != null)for(Object obj : list1) <. >in other words remove the curly braces around for this way you can keep it in one line
10 Answers 10
If possible, you should design your code such that the collections aren’t null in the first place.
null collections are bad practice (for this reason); you should use empty collections instead. (eg, Collections.emptyList() )
Alternatively, you could make a wrapper class that implements Iterable and takes a collections, and handles a null collection.
You could then write foreach(T obj : new Nullable(list1))
if you’re using generics it’s better to use Collections.emptyList() rather than Collections.EMPTY_LIST; it’s type safe.
@Dataknife More like it just does the casting for you. There are no generics types at runtime with either case, and the implementation of emptyList() internally contains the cast (with a suppression on unchecked too).
This turned out to be bad design for me. The place I placed them was then used by JAX — B to unmarshall data These lists are immutable and it would try and add to them. I think you should consider this too stackoverflow.com/questions/5552258/…
And empty list works great when you have the idea of a collection with nothing in it. That is subtly different than no collection; and, the difference can be significant. For example, when optional lists are represented as empty ones, you have to choose between handling it as a list or as nothing (the simplification removes one of the two options). This can be undesirable in some situations.