0

I have seen this question on SO that looks to convert a Map<String, Object> to a Map<String, String>. It tries to do a downcasting of the value of the map.

I have read the answers and it is required to iterate the map, downcast the value and put it in the new map (with different variations).

I am trying to do the opposite: I want to upcast the value. I want to convert a Map<String, SomeClass> to a Map<String, SomeUpperClass>, where SomeClass extends SomeUpperClass but I am having the same problem as the question I mentioned before.

Compiler tells me:

incompatible types: java.util.Map< java.lang.String, SomeClass> cannot be converted to java.util.Map< java.lang.String, SomeUpperClass>

I understand that downcasting can be dangerous and error prone, but I don't understand why I have to iterate the whole map to upcast values to put them in a new map.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
Sebastian D'Agostino
  • 1,575
  • 2
  • 27
  • 44
  • @SotiriosDelimanolis Are you sure the question is a duplicate? Map class in Java does not extend from Collection like List. Answers in the question I linked don't look anything like the one you flagged. – Sebastian D'Agostino Jul 02 '18 at 21:47
  • The actual generic type is inconsequential. The type could have any number of generic type parameters. The point, made by the accepted answer in the duplicate, is that if you were able to directly assign the one type to the other, you could add an object of some other subtype of `SomeUpperClass` and that would break type safety of the original map. Again, as the accepted answer suggests, you can assign your map to a variable of type `Map`. – Sotirios Delimanolis Jul 02 '18 at 21:52
  • Does that clear things up? – Sotirios Delimanolis Jul 02 '18 at 22:00
  • If you are already sure that types are right you can just cast this to `Map` without any generic type - but then you might get many issues and errors on get/put operations if some element is of invalid type. But if you already checked and you are sure that types are valid you can just use that raw-cast solution. – GotoFinal Jul 03 '18 at 07:58
  • Thanks @SotiriosDelimanolis. Yes, it was hard to understand at first but the answer should be "It's important to realize that a List is not interchangeable with a List". – Sebastian D'Agostino Jul 03 '18 at 13:32

0 Answers0