1

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;
    }
}
Rocket
  • 31
  • 6
  • 1
    You've defined a generic on the method `` (in your second to last example). You just need to actually use it in the rest of the code e.g. `Paar src, Paar dst` – Rogue May 26 '22 at 18:32
  • You can't provide the superclass as the parameter if the method accepts the subclass. That's not even generics. – Kayaman May 26 '22 at 18:33
  • @Rogue I changed it to `Paar src, Paar dst` the error still appears. – Rocket May 26 '22 at 18:40
  • You cannot pass `Speicher` to a method that accepts `Paar`. This would be akin to passing a `List` (e.g. a `LinkedList`) to a method which only accepts `ArrayList`. You could flip it around such that the method accepts all `Speicher` (including `Paar`), but the reverse isn't doable in this manner. – Rogue May 26 '22 at 18:45
  • @Rogue You are right. Weirdly this is a task from an exam from my university I took last semester. I'll contact my professor and ask him about it. Thanks! – Rocket May 26 '22 at 18:50

0 Answers0