This question regards gernerics, type-safty and Collection classes in Java:
Just as the title says: I have a method that returns a Collection, SortedMap<String,String>
, that I retrieve from say methodStrStr()
as return value. Say I call this method from methodStrSer()
that just needs to pass the retrieved map along but has to return SortedMap<String,Serializable>
.
What is an elegant non computationally expensive way to do so?
Without the generics I would have just returned the original map as String
is Serializable
. However I see that I might run into trouble at runtime if the underlying implementation of the SortedMap
would be specific to String
objects and result in errors if I wanted to add a different typed object such as Boolean
which is also Serializable
but not a String
. So I am aware that it makes sense, that the compiler does not allow to return a SortedMap<String,String>
as a SortedMap<String,Serializable>
.
However, I the question remains. Is there even an acceptable way to somhow "transform" (ie a way that does not take O(N) time) the original map type to the target type?