tags:

views:

74

answers:

6

I am creating an application which retrieve from an external party application an arraylist of Integer values. It seems that some of the elements in this retrieved list are empty or null. When I retrieve the size of the list for example:

System.out.println("The number of elements is : "+ elements_list.size());

it just throws an null pointer exception. Does anyone know a solution for such a problem? Thanks in advance!

+3  A: 

This means that the list you have received is null, it has nothing to do with its elements.

Robin
A: 

If

elements_list.size()

is throwing a null pointer exception, then the problem isn't that there are null items in the list. Rather, the call you're making to get the list is returning null (ie, not returning an actual list).

I'll admit i find it distasteful to return null when the code should be returning a list. Most of the time, the code should return the list (if it got values), an exception (if there was an error generating the values), or a empty list (if there were no values).

RHSeeger
+2  A: 

It's not complaining that a list element is null, it's complaining that the elements_list object itself is null. Check that elements_list is non-null before you do anything with it.

Nathan Hughes
+4  A: 

Your elements_list is null, so when you call the method size() it throws an exception. You can check if the list is null first by doing:

System.out.println("The number of elements is : "+ elements_list == null ? "0" : elements_list.size());

Or you can use Apache's CollectionUtils and call:

CollectionUtils.size(elements_list);

The CollectionUtils is null safe and will not throw a null pointer exception even if elements_list is null.

sdavids
+1  A: 

In the case of a NullPointerException in that code, the list itself is null. Wherever elements_list is being set, it is coming in as a null value. Check with your external party application and double-check any code that might be manipulating elements_list in between.

MikeG
+1  A: 

elements_list is null, so you can't call any method on it. The best way to do your test is to check both nullability and emptiness:

if (elements_list == null) || elements_list.isEmpty()) {
    ...
} else {
    ...
}
romaintaz