Java Method with Generics and Wildcard

57 views Asked by At

I have an issue with a task I have to solve. I have to create a static method 'copy' which gets two list-like generalised arguments and has to copy one in the other. I don't understand how to use generics in this specific case. Right now I get an error in the main class at the 'copy' part it says: 'The method copy(Paar<? extends Number>, Paar<? extends Number>) in the type Bounds is not applicable for the arguments (Speicher< Integer >, Speicher< Number >)'

But 'Paar' is an extention of 'Speicher'.

public class BoundsMain {

    public static void main(String[] args) {

        Integer[] iFeld = { 1, 2, 3 };
        Number[] nFeld = { 1.1, 2.2, 3.3 };
        Paar<Integer> src = new Paar<>(iFeld[0], iFeld[1]);
        Paar<Number> dst = new Paar<>(nFeld[0], nFeld[1]);
        System.out.println("src=" + src + "\ndst vor copy =" + dst );

        Bounds.copy(src, dst);
        System.out.println("src nach copy =" + src);
        System.out.println("dst nach copy =" + dst);

    }
}
public class Bounds {
    public static <T extends Number> void copy(Paar<? extends Number> src, Paar<? extends Number> dst) {
        Paar<T> copy = new Paar<>(null, null);
        copy.p1 = (T) src.p1;
        copy.p2 = (T) src.p2;
        dst = copy;
    }
}
public class Paar<T extends Number> extends Speicher<T> {
    T p1, p2;
    Paar(T p1, T p2){
        this.p1 = p1;
        this.p2 = p2;
    }
}
0

There are 0 answers