Java if ternary operator and Collections.emptyList()
您能解释一下为什么使用第一个返回类型时代码无法编译吗?消息是: 。Type mismatch: cannot convert from List<capture#1-of ? extends Object> to List<String>
在第二种情况下是否插入了显式强制转换?
public class GenericsTest {
private String getString() {
return null;
}
public List<String> method() {
String someVariable = getString();
//first return type
//return someVariable == null ? Collections.emptyList() : Collections.singletonList(someVariable);
//second return type
if (someVariable == null) {
return Collections.emptyList();
} else {
return Collections.singletonList(someVariable);
}
}
}