Search code examples
javacastingconcurrenthashmap

Cast ConcurrentHashMap<String, B> to ConcurrentHashMap<String, A> when B implements A


I have an interface called SerializableL that is implemented by 3 different classes:

  • Product
  • Banner
  • Tag

I started refactoring and wanted to replace multiple paragraphs with multiple method calls.

public void load(ConcurrentHashMap<String, SerializableL> map, 
ArrayList<SerializableForL> preparedList)

I've written the following code and get the following error.

Code:

ConcurrentHashMap<String, SerializableForL> test = DBStore.Cache.get(tag);

Error:

Type mismatch: cannot convert from ConcurrentHashMap<String,Banner> to 
    ConcurrentHashMap<String,SerializableForL>

How can I do a workaround?

I want a way to cast (ConcurrentHashMap<String,Banner> to ConcurrentHashMap<String,SerializableForL>) .

A banner IS a SerializableForL.


Solution

  • You can't assign a Map<String,Banner> to a Map<String,SerializableForL> even if Banner implements SerializableForL.

    However, if you only care about the values being SerializableForL you should be able to write:

    ConcurrentMap<String, ? extends SerializableForL> test = DBStore.Cache.get(tag);