2

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?

Nicolas
  • 755
  • 9
  • 22

1 Answers1

3

There are several options:

  • Copying the map - not recommended, because it may be expensive and not necessary
  • As izstas suggested: Changing the signature of the receiving to accept SortedMap<String, ? extends Serializable> (also see What is PECS (Producer Extends Consumer Super)? )
  • Just provide an appropriate view on the map.

The latter may be the most appropriate here. You can simply write

SortedMap<String, String> oldMap = ...;
SortedMap<String, Serializable> newMap = 
    Collections.<String, Serializable>unmodifiableSortedMap(oldMap);

This is safe, because the map is unmodifiable, and thus can not be "polluted" with Serializable objects that are not String. (A simple cast, resulting in a modifiable map, would of course not be type-safe - see this answer for an example why).

Community
  • 1
  • 1
Marco13
  • 53,703
  • 9
  • 80
  • 159