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.
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);
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With