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!
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
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());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.