G
Guest
Gast
Hallo,
kann mir bitte jemand erklären, warum der folgende Code nicht geht?
Soll eine Collection sein, die alle möglichen Typen von Zahlen akzeptiert
bzw. alles, was von Number abgeleitet ist (Integer, Double ...)
Ein anderes Beispiel (Basismodel + eine Erweiterung)
Die Fehlermeldung lautet
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Cannot instantiate the type ArrayList<? extends A>
Bound mismatch: The method add(? extends A) of type List<? extends A> is not applicable for the arguments (B). The wildcard parameter ? extends A has no lower bound, and may actually be more restrictive than argument B
Irgendeine Idee?
kann mir bitte jemand erklären, warum der folgende Code nicht geht?
Code:
List<? extends Number> list = new ArrayList<? extends Number>();
list.add(1);
list.add(2.5d);
bzw. alles, was von Number abgeleitet ist (Integer, Double ...)
Ein anderes Beispiel (Basismodel + eine Erweiterung)
Code:
class A {
private int a;
public A(int a) {
setA(a);
}
public int getA() {
return a;
}
public void setA(int a) {
this.a = a;
}
}
class B extends A {
private int b;
public B(int a, int b) {
super(a);
setB(b);
}
public int getB() {
return b;
}
public void setB(int b) {
this.b = b;
}
}
...
List<? extends A> list = new ArrayList<? extends A>();
list.add(new B(1,1));
list.add(new B(1,2));
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Cannot instantiate the type ArrayList<? extends A>
Bound mismatch: The method add(? extends A) of type List<? extends A> is not applicable for the arguments (B). The wildcard parameter ? extends A has no lower bound, and may actually be more restrictive than argument B
Irgendeine Idee?