Generics: cannot convert from Collections.emptyList () to <String> list
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 the security type of the empty list.
So return an empty list of strings like this
public List<String> getList(){ return isMyListReady() ? myList : Collections.<String>emptyList(); } To be more specific, see how you return the List<String> function. Therefore, when you use the ternary operator, your condition should also return a List<String> .
But in the case of Collections.emptyList() it is not of type List<String> . So you just need to specify the type of the empty collection. So just use Collections.<String>emptyList() .
The reason for the type mismatch is rather obscure and hidden in the logic of conditional expressions. In short, Java will try to determine the type of expression result by looking at the types of the second and third operands , which can lead to a hidden translation or binary action in the case of primitives! You can make this clearer if you extract each variable to a local one with the original type, and then look at your condition again.
I do not want to extract this chapter, but it is well explained in Java Puzzlers , chapter 8 of Dos Equis. Get a copy if you can, it's really worth it.