-1
public class Model extends LinkedHashMap<String, Object>{

}

LinkedHashMap<String, Object> map = //instance of LinkedHashMap

Model model = (Model) map  // Exception.

when I'm trying to cast LinkedHashMap<String,Object> into my Model class I'm getting class cast exception.

I'm basically using user defined method which expect Model as an argument that's why I'm casting my map into Model class

shadowhunter_077
  • 454
  • 1
  • 6
  • 13

3 Answers3

2

You cannot do that because Model is not an instanceof LinkedHashMap. Think in terms of memory allocation. What have you actually done? You have allocated enough memory for a LinkedHashMap but NOT for a Model. The compiler is trying to save you from yourself.

jiveturkey
  • 2,484
  • 1
  • 23
  • 41
  • `Model` is a type. It's never an instance of anything. Memory allocation isn't the issue here, it's type relationship. This answer completely missed the point, which is that downcasting, i.e., narrowing conversion of a reference always (!) risks a `ClassCastException`, as the JLS points out. http://docs.oracle.com/javase/specs/jls/se8/html/jls-5.html#jls-5.1.6 – Lew Bloch May 11 '17 at 17:14
1

You cannot use LinkedHashMap where Model is expected, therefore you cannot cast.

Presumably Model has additional methods and more functionality than LinkedHashMap. Even if you did not add anything new in Model class yet, Java assumes that you will.

Possible solution: change

LinkedHashMap<String, Object> map = //instance of LinkedHashMap

to

LinkedHashMap<String, Object> map = //instance of Model

Another solution: change the code that uses Model class to use Map instead.

Still another approach: do not derive Model from Map, have Model own a Map. Change the code accordingly.

In general, you need to learn more about OO programming, especially the modern sort that deprecates inheritance in favor of aggregation.

0

API Specifications for the ClassCastException says:

Thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance.

class P {
}
class C extends P {
}

P p = new P();
C c = (C) p;//java.lang.ClassCastException; Runtime Exception

If you really want to do it. You do it in this way:

LinkedHashMap map = new Model();
        map.put("one", "1");

        Model model = (Model) map; // Exception.
        System.out.println(model);

referece: Explanation of "ClassCastException" in Java

Community
  • 1
  • 1
Elias
  • 664
  • 2
  • 11
  • 23