Error in retrieving the size of an array list
I am creating an application which retrieve from an e开发者_如何学Goxternal 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!
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());
This means that the list you have received is null, it has nothing to do with its elements.
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.
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 {
...
}
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.
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.
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).
精彩评论