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