Nic*_*ray 8 java generics collections empty-list
为什么
public List<String> getList(){
if (isMyListOKReady())
return myList;
return Collections.emptyList();
}
Run Code Online (Sandbox Code Playgroud)
汇编得很好,但是
public List<String> getList(){
return isMyListReady() ? myList : Collections.emptyList();
}
Run Code Online (Sandbox Code Playgroud)
Eclipse说"Type mismatch: cannot convert from List<Object> to List<String>"?
Sac*_*hin 15
您需要注意空列表的类型安全性.
所以返回像这样的空字符串列表
public List<String> getList(){
return isMyListReady() ? myList : Collections.<String>emptyList();
}
Run Code Online (Sandbox Code Playgroud)
更具体地说,看看你的功能正在回归List<String>.因此,当您使用三元运算符时,您的条件也应该返回List<String>.
但是在Collections.emptyList()没有它的类型的情况下List<String>.所以只需要指定空集合的类型.所以只需使用Collections.<String>emptyList().
| 归档时间: |
|
| 查看次数: |
5099 次 |
| 最近记录: |