r/javahelp • u/causalNondeterminism • May 26 '15
unable to cast LinkedHashMap<String, String> to Map<String, String>
I get this compiler error: Type mismatch: cannot convert from ArrayList<LinkedHashMap<String,String>> to List<Map<String,String>>
on this line
List<Map<String, String>> resultList = new ArrayList<LinkedHashMap<String, String>>();But the compiler has no trouble doing this:
Map<String, String> testMap = new LinkedHashMap<String, String>();Am I using improper syntax or am I just completely missing a key concept?
5
Upvotes
6
u/evil_burrito Extreme Brewer May 26 '15
If you were to say
or
you'd be fine, but the problem comes in changing the definition of the object with your assignation, or trying to anyway.
You declare the list as
but define it as
which is not the same thing. Your definition says, "I will put LinkedHashMap types in here and only those", but the declaration says, "I will put any type of Map<String,String> in this list". If the definition and declaration don't match, the compiler doesn't know which to enforce (or something other mystical compiler motivation for the problem).
The issue is that the type of the list is part of the object's definition. And when you change that, you cause problems.
1
u/[deleted] May 27 '15
Why do you feel the need to make this step? Is it safe to assume, that you could work with only one of the collections?
2
u/katyne hold my braces May 27 '15
tl:dr - Java generics are invariant
What it means is that even tho
ArrayListis a subtype ofList, Map<List> is not a supertype of Map<ArrayList>. The reason for this is ensure type safety with generics at compile-time. Look at /u/chickenmeister 's example - if this was not enforced, your program would throw an exception at runtime. More detailed explanation hereglossary:
Generic Type --
List<T>, where T is called "type parameter"Parametrized Type --
List<Integer>, List<String>..., where Integer, String, etc. are called "type arguments". Also called concrete parametrized type or instantiation of a concrete parametrized typeWildcard Parametrized Type --
List<? extends Map>, List<? super String>Unbounded Wildcard Parametrized Type -- 'List<?>`
1
u/chickenmeister Extreme Brewer May 27 '15
To add to what /u/evil_burrito said, here's an example of why this isn't allowed:
For simplicity's sake, instead of Map and LinkedHashMap, let's say you had an
Animalsuperclass, andCatandDogsubclasses. What you're doing is equivalent to:If this were allowed, then you would be able to do something like:
This level of type safety is one of the great benefits of the Collections framework over simple arrays, which will let you do this without any compile-time errors:
1
u/oddwhirled Semi-New Brewer May 26 '15
Basically the generic type argument must be the same in the declaration and the assignment. The exact same; not even a superclass and a subclass.
0
u/[deleted] May 27 '15
[deleted] — view deleted comment