Could not downcast using List class in Java

Strategist picture Strategist · Mar 15, 2013 · Viewed 7.7k times · Source

I've been searching for an answer for this but to no avail. My question is why is it not possible to downcast with generics. I have a class called Job and extends a class called Model

Job extends Model

Now I get a collection of Jobs from a reusable code that generates a list of Models

// error: Cannot cast from List<Model> to List<Job>
List<Job> jobs = (List<Job>) jobMapper.fetchAll();

where jobMapper.fetchAll() returns a List where each model inside it is a Job object.

I assumed this would work because I can do:

EditText mUsername = (EditText) findViewById(R.id.editUserName);

which is a simple downcasting.

Answer

Leonidos picture Leonidos · Mar 15, 2013

You cant do this, because Java does not allows this. Read this. You should do the trick:

 List<Job> jobs = (List<Job>) ((List<?>)jobMapper.fetchAll());