Nic Stray
Nic Stray

Reputation: 184

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

Upvotes: 8

Views: 7855

Answers (2)

Sachin
Sachin

Reputation: 40970

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

Upvotes: 16

LastFreeNickname
LastFreeNickname

Reputation: 1455

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.

Upvotes: 2

Related Questions