Reputation: 63
I have a class (EntireFile) that extends the LinkedHashMap. I try to cast:
EntireFile old = (EntireFile) functionReturningLinkedHashMap();
It throws exception with message: "java.util.LinkedHashMap cannot be cast to com.gmail.maximsmol.YAML.GroupMap".
public class EntireFile extends LinkedHashMap<String, GroupMap>
public class GroupMap extends LinkedHashMap<String, CategoryMap>
public class CategoryMap extends LinkedHashMap<String, LinkedHashMap<String, Integer>>
Please help me to solve the error!
Upvotes: 3
Views: 2709
Reputation: 533492
Instead of casting you can copy the data to the type of map you need.
EntireFile old = new EntireFile(functionReturningLinkedHashMap());
or
EntireFile old = new EntireFile();
old.putAll(functionReturningLinkedHashMap());
Upvotes: 0
Reputation: 1500385
The problem is that the reference returned simply isn't a reference to an instance of EntireFile
. If functionReturningLinkedHashMap
just returns a LinkedHashMap
, it can't be cast to an EntireFile
, because it isn't one - how would it get any extra information about it?
(Judging by your exception, you're actually talking about GroupMap
rather than EntireFile
, but the same thing applies.)
There's nothing special about LinkedHashMap
here - the same is always true in Java:
Object foo = new Object();
String bar = (String) foo; // Bang! Exception
Upvotes: 5