3

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!

1
  • You are trying to downcast your LinkedHashMap to an EntireFile. If the cast does not work, that's because the runtime type of the object returned by your method is not an EntireFile. Commented Sep 17, 2012 at 14:46

2 Answers 2

5

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
Sign up to request clarification or add additional context in comments.

Comments

0

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());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.