【问题标题】:Return a Collections.emptyList() fails with ternary operator [duplicate]使用三元运算符返回 Collections.emptyList() 失败 [重复]
【发布时间】:2013-12-04 14:35:06
【问题描述】:

我有一个方法可以合并两个相同类型的列表。

public <T> List<T> mergeList(List<T> first, List<T> second) {


    if(first != null && second != null && (first.addAll(second))){

        return first;
    } else {

        return Collections.emptyList();
    }
}

如果使用 if-else-block 没有问题,但使用三元运算符:

public <T> List<T> mergeList(List<T> first, List<T> second) {

    return (first != null && second != null && first.addAll(second)) ? first : Collections.emptyList();

}

Eclipse 说:Type mismatch: cannot convert from List&lt;capture#1-of ? extends Object&gt; to List&lt;T&gt;

为什么我不能在这里返回Collections.emptyList()?我以为编译器会把三元运算符当作 if-else 处理?

【问题讨论】:

  • 你试过Collections.&lt;T&gt;emptyList();
  • 好吧,副本已经回答了......

标签: java generics collections ternary-operator


【解决方案1】:

你需要:

public <T> List<T> mergeList(List<T> first, List<T> second) {

  return (first != null && second != null && first.addAll(second)) 
    ? first 
    : Collections.<T>emptyList();

}

注意使用Collections.&lt;T&gt;emptyList() 而不是Collections.emptyList()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-22
    • 2017-03-28
    • 1970-01-01
    • 2011-05-23
    • 1970-01-01
    • 2018-07-24
    相关资源
    最近更新 更多