Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Could not downcast using List class in Java

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.

like image 750
Strategist Avatar asked Mar 15 '13 08:03

Strategist


People also ask

Why downcasting is not used in Java?

Upcasting is allowed in Java, however downcasting gives a compile error. The compile error can be removed by adding a cast but would anyway break at the runtime.

Can you downcast an object in Java?

Downcasting is done using cast operator. To downcast an object safely, we need instanceof operator. If the real object doesn't match the type we downcast to, then ClassCastException will be thrown at runtime.

Why is downcasting not allowed?

Downcasting is not allowed without an explicit type cast. The reason for this restriction is that the is-a relationship is not, in most of the cases, symmetric. A derived class could add new data members, and the class member functions that used these data members wouldn't apply to the base class.


1 Answers

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());
like image 191
Leonidos Avatar answered Oct 13 '22 06:10

Leonidos