Interface List - Objekt übergeben? Einzelnes Objekt geht, aber Liste nicht?

beta20

Top Contributor
Hallo,

ich habe ein Verständnisfrage und stehe hier gerade auf dem Schlauch...

Ich habe folgende Dinge:

Interface:
Java:
public interface DocumentPositionInterface

und eine Klasse, die das Interface implemntiert:
Java:
class OfferPosition implements  DocumentPositionInterface


Ich habe diese Liste:
List<OfferPosition> positionList = new ArrayList<OfferPosition>();

Diese möchte ich nun an eine Funktion übergeben:
Java:
List<DocumentPositionInterface> deletePosition(List<DocumentPositionInterface> positionList, DocumentPositionInterface positionToDelete)


Ich bekomme aber einen Compiler Fehler:
The method deletePosition(List<DocumentPositionInterface>, DocumentPositionInterface) in the type DocumentPositionCreatorProcessService is not applicable for the arguments (List<OfferPosition>, OfferPosition

Übergebe ich nur: deletePosition(DocumentPositionInterface positionToDelete) funktioniert es, wobei ich dann einen Fehler bekomme, weil der Rückgabewert (List<DocumentPositionInterface>) nicht passt..

Wo liegt mein Denkfehler?
 
Das Problem ist, dass eine List<OfferPosition> (dein aktuelles Argument) nicht zuweisungskompatibel zu einem List<DocumentPositionInterface> (der Parametertyp) ist. Generics sind nicht kovariant in ihren Typparameter.
Das kannst du beheben, indem du z.B. den Parametertyp nicht als List<DocumentPositionInterface> sondern als List<? extends DocumentPositionInterface> deklarierst.
 
habe hier nochmal eine Frage:
ich würde gerne der Liste ein Objekt hinzufügen (add):


private List<? extends DocumentPositionInterface> positionList = new ArrayList<DocumentPositionInterface>();

Also das hier:
DocumentPositionInterface offerPosition = wird gefüllt....;
positionList.add(offerPosition);

Ich bekomme dann aber diese Meldung:
The method add(capture#2-of ? extends DocumentPositionInterface) in the type List<capture#2-of ? extends DocumentPositionInterface> is not applicable for the arguments (DocumentPositionInterface)


Edit:
wäre das dann richtig:

List<? super DocumentPositionInterface> positionList = new ArrayList<DocumentPositionInterface>();
 
wäre das dann richtig:

List<? super DocumentPositionInterface> positionList = new ArrayList<DocumentPositionInterface>();
Was richtig ist, hängt immer davon ab, was genau du machen willst.

In so einem Fall wäre ein List<DocumentPositionInterface> positionList = new ArrayList<DocumentPositionInterface>(); am passendsten, Wildcards bei der Deklaration einer normalen Variable zu nutzen ist eher unüblich.



Wildcards nutzt man eher bei Methodenparametern, und da folgt man PECS: https://stackoverflow.com/a/2723538
 

Neue Themen


Zurück
Oben