泛型:无法从Collections.emptyList()转换为List< String> [英] Generics: Cannot convert from Collections.emptyList() to List<String>
问题描述
public List< String> getList(){
if(isMyListOKReady())
返回myList;
返回Collections.emptyList();
}
编译良好,但对于
public List< String> getList(){
返回isMyListReady()? myList:Collections.emptyList();
}
Eclipse表示类型不匹配:无法从List< ; Object> to List< String>
?
>类型安全的空列表。
因此,返回像这样的空字符串列表
public List< ;字符串> getList(){
返回isMyListReady()? myList:Collections。< String> emptyList();
$ b 更具体地说,看你的函数是否返回列表与LT;字符串>
。所以当你使用三元运算符时,你的条件也应该返回 List< String>
。
但是在 Collections.emptyList()
的情况下,它的类型不是列表与LT;字符串>
。所以只需要指定空集合的类型。所以只需使用 Collections。< String> emptyList()
。
Why
public List<String> getList(){
if (isMyListOKReady())
return myList;
return Collections.emptyList();
}
compiles well, but for
public List<String> getList(){
return isMyListReady() ? myList : Collections.emptyList();
}
Eclipse says "Type mismatch: cannot convert from List<Object> to List<String>"
?
解决方案 You need to take care of type safety of empty list.
So return the empty list of string like this
public List<String> getList(){
return isMyListReady() ? myList : Collections.<String>emptyList();
}
To be more specific, look you function is returning List<String>
. So when you are using ternary operator then your condition should also return List<String>
.
But in the case of Collections.emptyList()
doesn't have it's type as List<String>
. So Just need to specify the type of empty collection. So just use Collections.<String>emptyList()
.
这篇关于泛型:无法从Collections.emptyList()转换为List< String>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!