Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 386
Nic Stray Avatar asked May 28 '13 05:05

Nic Stray


2 Answers

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

like image 187
Sachin Avatar answered Sep 22 '22 12:09

Sachin


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.

like image 38
LastFreeNickname Avatar answered Sep 25 '22 12:09

LastFreeNickname