Abhik
Abhik

Reputation: 1940

Casting from ArrayList<Object> to ArrayList<Custom> class throws error while Object to Custom does not

I have an ArrayList deserializedArray that I have received by de-serializing JSON using GSON. I have my own class called Post. When I try to do this

 ArrayList<Post> posts =  (ArrayList<Post>) deserializedArray;

It throws exception saying in convertible types. But when I do this

Post P = (Post) deserializedArray.get(0);

This works fine.I am trying to understand why the first one doesn't work even though the second case works ?

Edit : I have been pointed to the solution. But what I really want to know is the inner workings of Java and why are there special restriction for lists ?

Upvotes: 0

Views: 522

Answers (1)

user1886323
user1886323

Reputation: 1199

The accepted way to do what you are trying to do is to use the Gson concept of a TypeToken. By using a TypeToken you elminate the need to cast at all (Gson will do this for you).

As for understanding why you get your particular error, check out this question.

Upvotes: 2

Related Questions