【问题标题】:Why does ternary operator fail with a type mismatch error?为什么三元运算符会因类型不匹配错误而失败?
【发布时间】:2014-11-06 02:22:58
【问题描述】:

我有以下简单的代码:

List<XXXXBean> queryPeriodData()
{
    if (CollectionUtils.isEmpty(res))
    {
        return Collections.emptyList();
    }

    return res;
}

有效。

但是如果我改成这个,就会出现编译错误...

return CollectionUtils.isEmpty(res) ? Collections.emptyList() : res;

错误信息是 “类型不匹配:无法从 List 转换为 List

我不知道这两种方式的区别。

【问题讨论】:

标签: java conditional type-inference ternary-operator


【解决方案1】:

在语句中尝试Collections.&lt;XXXXBean&gt;emptyList()

【讨论】:

  • 差异是因为:在第一个例子中,for语句“return Collections.emptyList();”编译器可以计算出返回类型。但在第二个示例中,在“Collections.emptyList()”表达式中,编译器不知道返回类型,因此默认返回 List。对吗?
猜你喜欢
  • 2020-05-27
  • 2021-06-30
  • 1970-01-01
  • 1970-01-01
  • 2020-04-18
  • 2016-06-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多