Ich schrieb ein kleines Stück Code für Sammlungen mit Generics und der Code ist wie unten.Learning Java Generics
Kann jemand erklären, was mit diesem Code falsch ist. Weil es folgenden Fehler wirft.
error: unexpected type
List<?> list1 = new ArrayList<?>();
^
required: class or interface without bounds
found: ?
HelloWorld.java:11: error: no suitable method found for add(String)
list1.add("Zahid");
^
method Collection.add(CAP#1) is not applicable
(argument mismatch; String cannot be converted to CAP#1)
method List.add(CAP#1) is not applicable
(argument mismatch; String cannot be converted to CAP#1)
where CAP#1 is a fresh type-variable:
CAP#1 extends Object from capture of ?
HelloWorld.java:12: error: no suitable method found for add(int)
list1.add(22);
^
method Collection.add(CAP#1) is not applicable
(argument mismatch; int cannot be converted to CAP#1)
method List.add(CAP#1) is not applicable
(argument mismatch; int cannot be converted to CAP#1)
where CAP#1 is a fresh type-variable:
CAP#1 extends Object from capture of ?
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
3 errors
Sie den generischen Typen ('Liste') oder "erlauben" alle Typen mit 'Liste angeben sollen erweitert Objekt> '. Aber die zweite Version hat keinen Vorteil, also sollten Sie die erste bevorzugen. –
@PJvG Er kompilieren kann 'Liste > list1 = new Arraylist >();' erfolgreich, aber als Slimu antwortete nur 'null' auf eine Liste mit unbeschränktem Wildcard Typ hinzufügen kann. –
@StefanWarminski richtig, ich formulierte es falsch, ich meinte er nicht tun kann 'Liste > list1 = new Arraylist >();' gefolgt von 'list1.add ("Zahid");'. Ich werde meinen Kommentar löschen, weil Slimus Antwort ausreichend ist, um das Problem zu erklären. – PJvG