List<Foo&g开发者_开发技巧t; results = null;
results = this.getResults();
if (results == null || results.size() == 0)
{
LOGGER.warn("results empty");
}
else
{
LOGGER.warn("results:" + results.toString());
}
The code above always produces the following output when getResults
returns a null List.
results:[null]
I need to respond to this null scenario but don't know how to catch it.
I think the results list has one item which is a null value.
I think the way is to check whether the list contains a null value at the the 0
th location, if not then the list contains at least one not null value.
List<Foo> results = null;
results = this.getResults();
if (results == null || results.size() == 0) {
LOGGER.warn("results empty");
} else if (list.get(0) == null){
LOGGER.warn("the list has only an null value");
} else {
LOGGER.warn("results:" + results.toString());
}
Or
List<Foo> results = null;
results = this.getResults();
if (results == null || results.size() == 0 || list.get(0) == null) {
LOGGER.warn("results empty");
} else {
LOGGER.warn("results:" + results.toString());
}
Based on your output, it looks like the List returned by getResults()
has one null element.
List<Foo> results = null;
results = this.getResults();
if (results == null || results.size() == 0) // you could add the check here
{
LOGGER.warn("results empty");
}
else if(results.size() == 1 && results.get(0) == null) // Or a new else if here
{
LOGGER.warn("all I've got is a null in my list :(");
}
else
{
LOGGER.warn("results:" + results.toString());
}
Everyone is correct that your list contains one null value. However, I don't understand why it's necessary to check to see if the first element is null. It looks more like you need to rethink what's going on in getResults()
and not put null in the list. I mean, there's no reason for us to assume there can't more more nulls, or nulls sitting in between actual objects.
精彩评论