List<Foo> results = null;
results = this.getResults();
if (results == null || results.size() == 0)
{
LOGGER.warn("results empty");
}
else
{
LOGGER.warn("results:" + results.toString());
}
当getResults
返回空列表时,上面的代码总是产生以下输出。
results:[null]
我需要回应这个空方案,但不知道如何捕捉它。
答案 0 :(得分:5)
我认为结果列表中有一个项为空值。
我认为方法是检查列表是否在0
位置包含空值,否则列表中至少包含一个非空值。
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());
}
或者
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());
}
答案 1 :(得分:1)
根据您的输出,看起来getResults()
返回的List有一个null元素。
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());
}
答案 2 :(得分:0)
每个人都是正确的,您的列表包含一个空值。但是,我不明白为什么有必要检查第一个元素是否为null。看起来你需要重新考虑getResults()
中的内容以及而不是在列表中放置null。我的意思是,我们没有理由假设没有更多的空值,或者在实际对象之间存在空值。