【发布时间】: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<capture#1-of ? extends Object> to List<T>
为什么我不能在这里返回Collections.emptyList()?我以为编译器会把三元运算符当作 if-else 处理?
【问题讨论】:
-
你试过
Collections.<T>emptyList(); -
好吧,副本已经回答了......
标签: java generics collections ternary-operator