Java List <Parent> and List <Children> method

Suppose we have:

public class Parent{
     public void setXXX(String XXX);
     public String getXXX();
}

public class Children extends Parent{
 ....
}

Now I want to create a clone List method, as shown below:

public List<Something> cloneList(List<Something> original){
    List<Something> newList=new ArrayList<>();
    for(Something e:original){
        Something newE=new Something();
        newE.setXXX(e.getXXX());
        newList.add(newE);
    }
    return newList;
}

We want cloneList to apply to List<Parent>both and to List<Children>, anyway, which applies to "Something"?

Something can't be "?" parent or parent since Java is Collection<Parent>not compatible withCollection<Children>

Assumption: 1. Do not want to use any serialization approach or reflection.

  1. We cannot change the Parent and Child class. This is predefined in a third-party bank.

  2. The SuperParent class is not possible, because we cannot modify Parent, as indicated in 2.

+4
source share
4

Java. .

SuperParent.

public static <T extends SuperParent> List<T> cloneList(List<T> original, Class<T> type) throws IllegalAccessException, InstantiationException {
    List<T> newList=new ArrayList<>();
    for(T e : original){
        T x = type.newInstance();
        x.setXXX(e.getXXX());
        newList.add(x);
    }
    return newList;
}

, . , Apache Commons 'SerializationUtils:

List<Children> result =  (List<Children>) SerializationUtils.clone(originalList);
+2

generics , .

T new T(). , generics - , new , . , :

new ArrayList<T>();

, raw ArrayList, :

new T();

, , ( T extends Parents, , , , Grandchildren - ), , .

+1

cloneList :

public <X extends Parent> List<X> cloneList(final List<X> original)

, , . List<Parent>, List<X> , ; "X".

0

, :

public <T extends Parent> List<T> cloneList(List<T> original)

. .

T newE = new T();  // doesn't work

T . , . , . :

public Parent Parent.copy();
public Children Children.copy();

... , :

public <T extends Parent> List<T> cloneList(List<T> original) {
    List<T> newList = new ArrayList<>();

    for (T originalItem : original) {
        newList.add(original.getClass().cast(original.copy()));
    }

    return newList;
}

( , Object.getClass() Class<?>, , , , , , .)

0

All Articles