使用三元运算符返回Collections.emptyList()失败

时间:2013-11-20 14:32:05

标签: java generics collections ternary-operator

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

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<capture#1-of ? extends Object> to List<T>

为什么我不能在此处返回Collections.emptyList()?我认为三元运算符将被编译器视为if-else?

1 个答案:

答案 0 :(得分:3)

你需要:

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

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

}

请注意使用Collections.<T>emptyList()代替Collections.emptyList()

相关问题