xylitol
xylitol

Reputation: 73

What's wrong with this null check?

List<Foo> 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.

Upvotes: 0

Views: 424

Answers (3)

Jeremy
Jeremy

Reputation: 22415

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.

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

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());
}

Upvotes: 5

Jonathon Faust
Jonathon Faust

Reputation: 12545

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());
}

Upvotes: 1

Related Questions