Cast <Son> list for <Father>

I have a simple POJO named "Father" and another "Son" that extends "Paternal", an example of a simple inheritance class.

Now I have it List<Son>, and I need to send it to List<Father>.

How can i do this?

EDIT

Sorry for the bad name, I myself have not explained. A Person and Employee would be the best example. Or Product and Computer .

+5
source share
4 answers

2 offers:

Have an interface, let's say Personthat Father(and therefore Son) implements. Use List<Person>for both.

new List<Father> Constructor, . List<Father> fathers = new ArrayList<Father>(sons);

+3

*, . (.. ):

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

* - cf : List<Father> listFather = (List<Father>) (List<? extends Father>) listSons;

+3

Suppose you can do this with a throw, this will lead to the following problem:

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

Both lsand lfare pointing to the same instance, so you just add the object Fatherto the list of Sons.

+3
source

It works:

static class Father {};
static class Son extends Father{};

public void test() {
  List<Son> sons = new ArrayList<>();
  // Not allowed.
  //List<Father> sons2 = (List<Father>)sons;
  // Two step.
  List<? extends Father> sons3 = sons;
  List<Father> sons4 = (List<Father>)sons3;
  // Direct.
  List<Father> sons5 = (List<Father>)((List<? extends Father>)sons);
}
+2
source

All Articles