Reputation: 4305
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!
Upvotes: 2
Views: 30016
Reputation: 1537
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());
Upvotes: 16
Reputation: 21
I had the same problem.
if (list==null || list.size()==0) //throws exception
The list is not null
but the size cannot be determined. The problem was that the collection was read from the DB with 'lazy' on. Hence it was not totally read and so The .size()
call throws a 'NullPointerException'. Reading the entire collection takes care of the problem.
Upvotes: 2
Reputation: 81667
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 {
...
}
Upvotes: 2
Reputation: 4793
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.
Upvotes: 1
Reputation: 96454
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.
Upvotes: 3
Reputation: 16282
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).
Upvotes: 0
Reputation: 24282
This means that the list you have received is null, it has nothing to do with its elements.
Upvotes: 8