Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast List<Son> to List<Father>

I have a simple POJO named "Father" and another one named "Son" which extends "Father", the simplest class inheritance example.

Now I have a List<Son> and I need to cast it to a List<Father>.

How can I do?

EDIT

Sorry for the bad naming, I didn't explain myself. Person and Employee would have been a better example. Or Product and Computer, too.

like image 645
Fabio B. Avatar asked Feb 27 '13 12:02

Fabio B.


3 Answers

2 suggestions:

Have an Interface, say Person, that Father (and thus Son) implements. Use List<Person> for both.

Create a new List<Father> with the collection Constructor, e.g. List<Father> fathers = new ArrayList<Father>(sons);

like image 58
frIT Avatar answered Oct 01 '22 13:10

frIT


Assume for a moment you could do that with a cast, it would lead to the following problem:

List<Son> ls = ...;
List<Father> lf = (List<Son>) ls;
lf.add(new Father());

Both ls and lf point to the same instance so you have just added a Father object into a list of Sons.

like image 20
Henry Avatar answered Oct 01 '22 14:10

Henry


You can't use a cast here* as commented above. You could write a small helper method to do the conversion (i.e.the copy):

private static List<Father> getListFather(List<? extends Father> list) {
    return new ArrayList<> (list);
}

* Actually you can - cf the other answer: List<Father> listFather = (List<Father>) (List<? extends Father>) listSons;

like image 20
assylias Avatar answered Oct 01 '22 15:10

assylias