Für das folgende Code-Beispiel:Java Generics: Zuordnung mit verschachtelten Platzhalter Parameter
public static class Abc<X> { }
public static class Def<Y> { }
public static class Ghi<Z> { }
public void doThis() {
List<?> listOne;
List<Abc<?>> listTwo;
List<Abc<Def<?>>> listThree;
List<Abc<Def<Ghi<?>>>> listFour;
List<Abc<Def<Ghi<String>>>> listFive;
Abc<Def<Ghi<String>>> abcdef;
abcdef = new Abc<Def<Ghi<String>>>();
listOne.add(abcdef); // line 1
listTwo.add(abcdef); // line 2
listThree.add(abcdef); // line 3
listFour.add(abcdef); // line 4
listFive.add(abcdef); // line 5
}
Zeilen 1, 3 und 4 nicht kompilieren:
(line 1)
The method add(capture#1-of ?) in the type List<capture#1-of ?> is not applicable for the arguments (Abc<Def<Ghi<String>>>)
(Zeile 3)
The method add(Abc<Def<?>>) in the type List<Abc<Def<?>>> is not applicable for the arguments (Abc<Def<Ghi<String>>>)
(Linie 4)
The method add(Abc<Def<Ghi<?>>>) in the type List<Abc<Def<Ghi<?>>>> is not applicable for the arguments (Abc<Def<Ghi<String>>>)
Linien 2 und 5, jedoch kompilieren.
Kann jemand erklären, warum die Zeilen 1, 3 und 4 keine legalen Zuweisungen sind? Und wenn Wildcard-Parameter in diesen Zeilen nicht auf diese Weise verwendet werden können, warum ist dann die Zuweisung in Zeile 2 legal?
Sehr gute Frage! Für * Zeile 1 * liegt das daran, dass Sie nichts zu einer Liste mit unbekanntem Typ hinzufügen können, außer "null". – rlegendi