maximsmol
maximsmol

Reputation: 63

java cast LinkedHashMap to class extending LinkedHashMap

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

Answers (2)

Peter Lawrey
Peter Lawrey

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

Jon Skeet
Jon Skeet

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

Related Questions