Generics: Cannot convert from Collections.emptyList() to List<String>

末鹿安然 提交于 2019-12-08 17:02:51

问题


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>"?


回答1:


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




回答2:


The reason for the type mismatch is quite obscure and hidden in the logics of conditional expressions. In short, Java will try to determine the result type of the expression by looking at the types of the second and third operand, which may lead to a hidden cast or binary promotion in case of primitives! You can make it clearer, if you extract every variable into a local one with the original type and then look at your condition again.

I don't want to extract the chapter, but it is well explained in Java Puzzlers, chapter 8 Dos Equis. Get a copy of it if you can, it's really worth it.



来源:https://stackoverflow.com/questions/16784865/generics-cannot-convert-from-collections-emptylist-to-liststring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!