泛型:无法从Collections.emptyList()转换为List <String>

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().

  • "需要注意类型安全"有点模糊 - 正在发生的事情是编译器无法在三元表达式中推断出正确的类型参数,因此您需要明确指定它. (4认同)