开发者

What's wrong with this null check?

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 0th 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜